【问题标题】:How to deal with setState properly如何正确处理setState
【发布时间】:2020-07-04 10:29:41
【问题描述】:
void showSimpleCustomDialog(BuildContext context, String listName) async{
if(randList.isEmpty){
    randList = await theDb.queryWhere("$listName");
  }else{
    randList.clear();
    randList = await theDb.queryWhere("$listName");
  }
setState((){
});
String randValue = "Click generate new to get a random value";
Dialog simpleDialog = Dialog(
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(12.0),
  ),
  child: Container(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Padding(
          child: Text(
            "$randValue"
          ),
        ),
        Padding(
          child: Row(
            children: <Widget>[
              RaisedButton(
                color: Colors.blue,
                onPressed: () 
                  String lol = randList[0 + rng.nextInt(randList.length - 0)].getItem();                        
                  print(randValue);
                  setState(() {
                    randValue = lol;
                  });
                },
                child: Text(
                  'generate new',
                  style: TextStyle(fontSize: 18.0, color: Colors.white),
                ),
              )
            ],
          ),
        ),
      ],
    ),
  ),
);
showDialog(
    context: context, builder: (BuildContext context) => simpleDialog);}

当我单击“生成新”按钮时,我想更新我的 randomValue 并将该 randomValue 显示为文本小部件。我使用 setState 动态地做到这一点,但它不起作用,我不明白为什么。请帮帮我。

【问题讨论】:

    标签: flutter dart setstate


    【解决方案1】:

    您应该在对话中使用 StatefulBuilder。

     showDialog(
          context: context,
          builder: (context) {
            String contentText = "Content of Dialog";
            return StatefulBuilder(
              builder: (context, setState) {
                return AlertDialog(
                  title: Text("Title of Dialog"),
                  content: Text(contentText),
                  actions: <Widget>[
                    FlatButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text("Cancel"),
                    ),
                    FlatButton(
                      onPressed: () {
                        setState(() {
                          contentText = "Changed Content of Dialog";
                        });
                      },
                      child: Text("Change"),
                    ),
                  ],
                );
              },
            );
          },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多