iT邦幫忙

2022 iThome 鐵人賽

DAY 20
0
Mobile Development

在 Flutter 開發旅程的手札系列 第 20

Flutter Package — 用日曆選擇日期

  • 分享至 

  • xImage
  •  

今天要介紹透果使用flutter_datetime_picker來選擇日期

安裝套件

flutter pub add flutter_datetime_picker

套件下載後,如果看到有下方警告訊息

../.asdf/installs/flutter/3.0.5-stable/.pub-cache/hosted/pub.dartlang.org/flutter_datetime_picker-1.5.1/lib/flutter_datetime_picker.dart:311:32: Warning: Operand of null-aware operation '??' has type 'Color' which excludes null.
 - 'Color' is from 'dart:ui'.
                  color: theme.backgroundColor ?? Colors.white,

https://ithelp.ithome.com.tw/upload/images/20221005/20152683aqmHkW6Whs.png

可以到pubspec.yaml檔案,將flutter_datetime_picker改為下方語法

  flutter_datetime_picker:
    git:
      url: https://github.com/Realank/flutter_datetime_picker.git
      ref: master

https://ithelp.ithome.com.tw/upload/images/20221005/20152683XbipCP1OuY.png

新增datetime_screen.dart輸入下方語法

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

class DatetimeScreen extends StatefulWidget {
  const DatetimeScreen({Key? key}) : super(key: key);

  @override
  State<DatetimeScreen> createState() => _DatetimeScreenState();
}

class _DatetimeScreenState extends State<DatetimeScreen> {
  DateTime dateTime = DateTime.now();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: ElevatedButton(
        onPressed: () {
          DatePicker.showDatePicker(context, showTitleActions: true, onConfirm: (date) {
            setState(() {
              dateTime = date;
            });
          }, currentTime: dateTime, locale: LocaleType.zh);
        },
        child: Text(dateTime.toString()),
      ),
    ));
  }
}

DateTime Demo 1

如果不想要顯示後面的時間,能下載intl套件,使用DateFormat來達成我們想要的效果

flutter pub add intl

Text(dateTime.toString())改為

Text(DateFormat("yyyy-MM-dd").format(dateTime)),

https://ithelp.ithome.com.tw/upload/images/20221005/20152683AmIl0uo6In.png


上一篇
Flutter Package - 分享連結、文字
下一篇
Flutter Package - Bloc(一)
系列文
在 Flutter 開發旅程的手札30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言