效果图:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
class DatePickerDemo extends StatefulWidget {
DatePickerDemo({Key key}) : super(key: key);
_DatePickerDemoState createState() => _DatePickerDemoState();
}
class _DatePickerDemoState extends State<DatePickerDemo> {
DateTime _selectDate = DateTime.now();
TimeOfDay _selectTime = TimeOfDay.now();
//选择日期的方法
_selectDateMethod () async {
debugPrint('选择时间方法');
final DateTime date = await showDatePicker(
context: context,
initialDate: _selectDate,
firstDate: DateTime(1998),
lastDate: DateTime(2029),
);
if(date == null) return;
setState(() {
_selectDate = date;
});
}
//Future表示异步的返回值 必须使用async
Future <void> _selectTimeMethod () async {
debugPrint('选择时间方法');
final TimeOfDay timeOfDay = await showTimePicker(
context: context,
initialTime: _selectTime,
);
if(timeOfDay == null) return;
setState(() {
_selectTime = timeOfDay;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DatePicker'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
splashColor: Colors.green,
onTap: (){
_selectDateMethod();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('日期选择'),
Text(DateFormat().add_yMd().format(_selectDate)),
Icon(Icons.arrow_drop_down)
],
),
),
InkWell(
splashColor: Colors.green,
onTap: (){
_selectTimeMethod();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('时间选择'),
Text(_selectTime.format(context)),
Icon(Icons.arrow_drop_down)
],
),
)
],
),
);
}
}