如何正确处理setState

时间:2020-07-04 10:29:41

标签: flutter dart setstate

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,但它无法正常工作,我也不明白为什么。请帮助我。

1 个答案:

答案 0 :(得分: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"),
                ),
              ],
            );
          },
        );
      },