class DatePickerDemo extends StatefulWidget { DatePickerDemo({Key key}) : super(key: key); @override _DatePickerDemoState createState() => _DatePickerDemoState(); } class _DatePickerDemoState extends State<DatePickerDemo> { DateTime _date = DateTime.now(); TimeOfDay _time = TimeOfDay.now(); Future<void> _selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: context, initialDate: _date, //起始时间 firstDate: DateTime(2020, 1), //结束时间 lastDate: DateTime(2021, 1), ); if (picked != null && picked != _date) { setState(() { _date = picked; }); } } Future<void> _selectTime(BuildContext context) async { final TimeOfDay picked = await showTimePicker( context: context, initialTime: _time, ); if (picked != null && picked != _time) { setState(() { _time = picked; }); } } @override Widget build(BuildContext context) { return Center( child: Column( children: [ Text('日期选择'), RaisedButton( child: Text('选择结果:${_date.toString()}'), onPressed: () { _selectDate(context); }, ), Text('时间选择'), RaisedButton( child: Text('选择结果:${_time.toString()}'), onPressed: () {}, ), ], ), ); } }
Flutter笔记21:showDatePicker和showTimePicker方法
Flutter的showDatePicker和showTimePicker方法,可以调用原生的日期选择框和时间选择框,两个方法都是Future方法,因为选择的结果需要等待选择完毕才能得到: