简体   繁体   English

Flutter - 值正在更新,但如果 state 不再工作

[英]Flutter - value is being updated but if state doesn't work again

 for (var i = 0; i < 10; i++)
        for (var j = 0; j < 3; j++)
          Positioned(
              top: size.height * 0.40 * j / 6,
              left: size.width * 0.09 * i,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: size.width * 0.09,
                          vertical: size.height * 0.40),
                      child:
                          (datesinmonth.contains("19"))
                              ? CircleButton(color: Colors.green)
                              : CircleButton(color: Colors.red))
                ],
              )),

   CupertinoActionSheetAction(
                            onPressed: () {
                              Navigator.pop(context);
                              setState(() {
                                selectedMonth = searchinmonths;
                                datesinmonth =
                                    FirebaseAuthenticationService.dateCheck(
                                            selectedMonth)
                                        .toString();
                                log(datesinmonth);
                              });
                            },
                            child: Text("Done")),

On the code above if the string "datesinmonth" contains a date, the corresponding circle must be printed green.在上面的代码中,如果字符串“datesinmonth”包含日期,则相应的圆圈必须打印为绿色。 The data which is "17" is being fetch from the database and assigned to the variable "datesinmonth".正在从数据库中获取“17”的数据并分配给变量“datesinmonth”。 I checked and the value is being updated as I wanted but the if statement doesn't work.我检查并按照我的意愿更新了值,但是 if 语句不起作用。 How can I solve that?我该如何解决? Thanks.谢谢。

I solved the problem the solution was changing of我解决了解决方案正在改变的问题

datesinmonth = FirebaseAuthenticationService.dateCheck(selectedMonth) as String;

The reason that you have to change the value twice is because setState runs before FirebaseAuthenticationService.dateCheck(selectedMonth).toString();您必须更改该值两次的原因是setStateFirebaseAuthenticationService.dateCheck(selectedMonth).toString();之前运行finishes.完成。 To solve this simply add the await keyword to the beginning of the line, and make the onPressed function asynchronous:要解决这个问题,只需将await关键字添加到行首,并使 onPressed function 异步:

onPressed: () async {
    Navigator.pop(context);
    setState(() {
      selectedMonth = searchinmonths;
      datesinmonth = await FirebaseAuthenticationService.dateCheck(selectedMonth).toString();
      log(datesinmonth);
    });
  },

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

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