因为是通过方法调用的组件,所以都必须通过方法来调用,不能按组件方式来生成
日历选择器组件方法:
1、先通过DateTime生成时间对象
2、在方法中设置
showDatePicker(
context:context,
initialDate: 时间对象, 初始化时间
firstDate: DateTime(1980), 从当前到1980都是高亮显示
lastDate: DateTime(2030), 从当前到2020都是高亮显示
其中还可在firstDate和lastDate分别填入:
now.subtract(new Duration(days: 30)), //从当前天开始,前面高亮的天数
now.add(new Duration(days: 30)), //从当前天开始,后面天高亮的天数
).then((res){
参数为点击确定后选定的年月日
});
时间时钟选择器组件方法:
1、通过TimeOfDay(hour: n,minute: n2); 赋值给变量
2、在方法中设置
showTimePicker(
context:context,
initialTime:时间变量
).then((x){
参数为TimeOfDay(19:40)形式的字符串,在Widget build方法中通过
xx.format(context)转换成7:40 PM的形式
});
代码示例:
import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
class Home4 extends StatefulWidget {
Home4({Key key}) : super(key: key);
@override
_Home2State createState() => _Home2State();
}
class _Home2State extends State<Home4> {
DateTime now = new DateTime.now();
var time=TimeOfDay(hour: 12,minute: 40);
_showDatePicker()
{
showDatePicker(
context:context,
initialDate: now, //初始化时间
firstDate: DateTime(1980), //从当前到1980都是高亮显示
lastDate: DateTime(2030), //从当前到2020都是高亮显示
//now.subtract(new Duration(days: 30)), //从当前天开始,前面高亮的天数
//now.add(new Duration(days: 30)), //从当前天开始,后面天高亮的天数
).then((res){ //Futur类型的方法类似promise对象,.then或者await获取返回值
print(res); //参数为点击确定后选定的年月日
setState(() {
this.now=res;
});
});
}
showTime()
{
showTimePicker(
context:context,
initialTime:time
).then((time2){
print(time2);
setState(() {
this.time=time2;
});
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(children: <Widget>[
//当前时间
// Text(now.hour.toString()),
//时间戳
// Text(now.millisecondsSinceEpoch.toString()),
//DateTime.fromMillisecondsSinceEpoch(时间戳); 将时间戳转换成日期
//点击水波纹组件
InkWell(
child: Row(children: <Widget>[
Text("${formatDate(now, [yyyy, '年', mm, '月', dd])}"),
Icon(Icons.calendar_today)
],),
onTap: this._showDatePicker
),
InkWell(
child: Row(children: <Widget>[
Text(time.format(context)),
Icon(Icons.calendar_today)
],),
onTap: (){
showTime();
}
)
]),
);
}
}
// 因为表单组件需要改变状态,所以要使用有状态组件
/*
flutter pub get
*/