今天要介紹透果使用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,
可以到pubspec.yaml檔案,將flutter_datetime_picker
改為下方語法
flutter_datetime_picker:
git:
url: https://github.com/Realank/flutter_datetime_picker.git
ref: master
新增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()),
),
));
}
}
如果不想要顯示後面的時間,能下載intl套件,使用DateFormat
來達成我們想要的效果
flutter pub add intl
將Text(dateTime.toString())
改為
Text(DateFormat("yyyy-MM-dd").format(dateTime)),