如何根据文本字段的输入来更改按钮的文本

时间:2019-09-30 06:38:21

标签: flutter

我有一个带有“删除”按钮的小弹出窗口,但是我想每次输入的文本不同于0.00时将文本更改为“卖”。

showDialog(
        context: context,
        builder: (context) {
          String _popUpDeleteSoldText = "Delete";
          return AlertDialog(
            title: Text("Delete " + doc['propertyName'] + "?"),
            content: Container(
              height: 120,
              child: Column(
                children: <Widget>[
                  TextField(
                    onChanged: (text) {
                      if (text != "0.00") {
                        print("i'm != 0.00");
                        setState(() {
                          //TODO - THIS AIN'T WORKING
                          _popUpDeleteSoldText = "Sell";
                        });
                      } else {
                        print("i'm still 0");
                        setState(() {
                          _popUpDeleteSoldText = "Delete";
                        });
                      }
                    },

按钮:

MaterialButton(
                elevation: 4.0,
                child: Text(
                  _popUpDeleteSoldText,
                  style: TextStyle(color: Colors.white),
                )
....

打印正在使用onChange函数,但是按钮文本始终显示“删除”

2 个答案:

答案 0 :(得分:0)

我建议将AlertDialog提取到单独的StatefulWidget中,然后它将起作用。

答案 1 :(得分:0)

您可以像下面的示例一样直接用StatefulBuilder包装
使用setState

后,字符串contentText将更改
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"),
            ),
          ],
        );
      },
    );
  },
);