IconButton(
onPressed: () async {
DateTime? x = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2040));
if (x == null) return;
setState(() {
final DateFormat formatter = DateFormat('yyyy-MM-dd');
String formattedDate = formatter.format(x);
print(formattedDate);
print(formattedDate.runtimeType);
});
},
icon: const Icon(UniconsLine.clock)),
Text(formattedDate ?? "EMPTY"),
我看到总是空我的formattedDate变量下面的构建方法为什么不工作这个代码
你能试着抬起formattedDate吗?我认为问题是你的变量超出了作用域。
class DatePicker extends StatefulWidget {
const DatePicker({Key? key}) : super(key: key);
@override
State<DatePicker> createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
String? formattedDate;
@override
Widget build(BuildContext context) {
return Column(children: [
IconButton(
onPressed: () async {
DateTime? x = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2040));
if (x == null) return;
setState(() {
final DateFormat formatter = DateFormat('yyyy-MM-dd');
formattedDate = formatter.format(x);
print(formattedDate);
print(formattedDate.runtimeType);
});
},
icon: const Icon(Icons.date_range)),
Text(formattedDate ?? "EMPTY"),
]);
}
}
问题在变量formattedDate的作用域中。它只存在于setState中,因为它是在那里声明的。
在类的开头声明。
您已经将setState()
中的formattedDate
重新定义为局部变量。您在Text(formattedDate ?? "EMPTY")
中使用的字段formattedDate
是一个完全不同的变量。它保持为空,因为您根本没有更改它。只要在formattedDate
之前去掉String
,就可以了。
final DateFormat formatter = DateFormat('yyyy-MM-dd');
formattedDate = formatter.format(x); <-- This is your problem
print(formattedDate);