【发布时间】:2020-06-26 15:47:33
【问题描述】:
我想知道如何在 Flutter 的小部件中使用 if 语句。
下面的代码提示用户使用 DateRange 包选择日期范围。我正在尝试接收日期输入,并使用 Text(...) 进行打印。
但是,我使用的 if 语句:
Text((() {
if(condition){
return habitDates[0].toString() + "to " + habitDates[1].toString();}
return "Pick Date";
})()),
似乎没有更新(它一直是“选择日期”),我认为这是关于小部件状态的问题。
以下是完整代码:
class DateRange extends StatefulWidget {
@override
_DateRangeState createState() => _DateRangeState();
}
class _DateRangeState extends State<DateRange> {
List<DateTime> habitDates = [];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
MaterialButton(
color: Colors.grey[700],
onPressed: () async {
final List<DateTime> picked = await DateRagePicker.showDatePicker(
context: context,
initialFirstDate: new DateTime.now(),
initialLastDate: (new DateTime.now()),
firstDate: new DateTime(2020),
lastDate: new DateTime(2030),
);
if (picked != null && picked.length == 2) {
picked.forEach((date) {
habitDates.add(date);
print(habitDates);
}
);
}
},
child: Text("Pick date range", style: TextStyle(color: Colors.white),)
),
Text((() {
if(habitDates != null && habitDates.length == 2){
return habitDates[0].toString() + "to " + habitDates[1].toString();}
return "Pick Date";
})()),
],
);
}
}
【问题讨论】:
-
Text(condition? 'first text' : 'second text') -
如果我按照您的建议进行操作,则条件不会更新(它仍然为假)。我相信我需要更新 Widget 的状态。您是否认为创建 2 个单独的类并更新状态以通知其他作品?
-
如果您在
build中使用habitDates,那么每次更改habitDates时都必须调用setState()方法-flutter.dev/docs/development/ui/…