Flutter 警报对话框 setState 未更改

时间:2021-06-21 15:20:16

标签: flutter dart

我正在尝试更改对话框中的一些布尔值。我就是这样做的

   showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            bool testBool = true;
            return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                  BorderRadius.circular(12.0),
                  side: BorderSide(
                      color:
                      kPrimaryColor)), //this right here
              child: GestureDetector(
                onTap: (){
                  print(testBool);
                  setState((){
                    testBool = !testBool;

                  });
                  print(testBool);
                },
                child: Container(
                  height: 525,
                  width: width * 0.85,
                  child:
                  Text('12313', style: TextStyle(color: testBool? Colors.red : Colors.green),),
                ),
              ),
            );
          },
        );
      },
    );

但它没有改变颜色,我的意思是说它没有改变 Dialog 中的 testBool 状态。

3 个答案:

答案 0 :(得分:1)

您的代码很好,但您将 bool 条件放在 builder 中,这就是为什么每次调用 setState 时它都会再次设置为 true。< /p>

showDialog(
  context: context,
  builder: (context) {
    bool testBool = true; // This flag should be here.
    return StatefulBuilder(
      builder: (context, setState) {
        // ... 
      },
    );
  },
);

答案 1 :(得分:0)

您必须在 testbool 之外定义变量 StatefulBuilder,因为每当您执行 setState 时,StatefulBuilder 下的程序都会重建,因此变量 testbool再次定义。

答案 2 :(得分:0)

正如 CopsOnRoad 提到的,bool testBool = true; 位于错误的位置。当您调用 setState 时,它​​会重新构建小部件,而在重新构建小部件时,它会定义 testBool 并将其设置为 true。变量 testBool 应该是正在构建对话框的状态类中的一个字段。