这是带有Cupertino日期选择器的小型表格。 我想在表格上显示初始日期。点按文本字段后,它将显示一个日期选择器,一旦选择了新日期,它将显示新日期
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
const double _kPickerSheetHeight = 216.0;
class AddCashPage extends StatefulWidget {
@override
_AddCashPageState createState() => _AddCashPageState();
}
class _AddCashPageState extends State<AddCashPage> {
final _formKey = GlobalKey<FormState>();
DateTime date = DateTime.now();
DateTime newDateTime;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Form(
key: _formKey,
child: buildTextFormField(),
),
],
),
);
}
Widget buildTextFormField() {
return Column(
children: <Widget>[
GestureDetector(
onTap: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return _buildBottomPicker(
CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: date,
onDateTimeChanged: (DateTime addSelectedDate) {
setState(() {
this.newDateTime = addSelectedDate;
date = newDateTime;
});
},
),
);
},
);
},
child: _buildMenu(
<Widget>[
//Show initial date here
Text(
DateFormat.yMMMMd().format(newDateTime),
),
],
),
),
],
);
}
}
我已将date = newDateTime;
添加到setState
,并且Text(DateFormat.yMMMMd().format(newDateTime),)
仍为null。我正在考虑使用三元运算符,或者有更好的方法
答案 0 :(得分:0)
使用initState
方法为newDateTime
设置初始值
void initState() {
super.initState();
newDateTime = DateTime.now();
}