简体   繁体   English

渲染 Text() 时,小部件内的 Flutter If 语句

[英]Flutter If Statement within Widget when rendering Text()

I was wondering how to use if statements within widgets in Flutter.我想知道如何在 Flutter 的小部件中使用 if 语句。

The code below prompts the user to choose a date range using the DateRange package.下面的代码提示用户使用 DateRange 包选择日期范围。 I am trying to receive the date input, and print it using Text(...).我正在尝试接收日期输入,并使用 Text(...) 打印它。

However, the if statement that I am using:但是,我正在使用的 if 语句:

        Text((() {
          if(condition){
            return habitDates[0].toString() + "to " + habitDates[1].toString();}
          return "Pick Date";
        })()),

does not seem to update (it's constantly "Pick Date"), and I assume it is an issue regarding the widget's state.似乎没有更新(它一直是“选择日期”),我认为这是关于小部件状态的问题。

Below is the full code:下面是完整的代码:

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";
        })()),
      ],
    );
  }
}

You can call setState(() {...});你可以调用 setState(() {...}); for update your Text Widget.用于更新您的文本小部件。 Like this.像这样。

if (picked != null && picked.length == 2) {
  setState(() {
    picked.forEach((date) {
      habitDates.add(date);
      print(habitDates);
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM