【问题标题】:Does setState() have any limitations with regard to updating UIsetState() 在更新 UI 方面是否有任何限制
【发布时间】:2019-05-30 04:40:43
【问题描述】:

我正在尝试更新 TextField 以显示错误文本,直到电子邮件被外部 validators 包验证。但是,即使我从 build 方法中调用 setState,UI 也不会更新。我尝试使用print 语句(附截图)进行调试,并且行为符合预期。如果我尝试在setState() 中传递更新的TextField UI,为什么UI 不更新显示带有错误文本的TextField?

有效的代码

无效的代码

                    child:  TextField(
                      decoration: InputDecoration(
                          hintText: "Enter Email Id",
                          border: OutlineInputBorder()),
                      onChanged: (String value) {
                        emailId = value;
                        setState(() {
                          isEmail(value)
                              ? print("true")
                              : TextField(
                                  decoration: InputDecoration(
                                      errorText: "Enter valid email"),
                                );
                        });
                      },

【问题讨论】:

  • 不要发布您的代码/日志的屏幕截图。以文本形式发布并使用文本工具框进行格式化
  • 我使用截图显示输出日志。

标签: flutter setstate


【解决方案1】:

您的代码不起作用,因为您没有更改父小部件的状态 在其onChanged: 属性中。您正在设置状态下创建一个新小部件

child: TextField( //parent
      decoration: InputDecoration(
      hintText: "Enter Email Id",
      border: OutlineInputBorder()),
              onChanged: (String value) {
              emailId = value;
              setState(() {
                 isEmail(value)
                    ? print("true")
                    : TextField( //this is not the same widget.
                        decoration: InputDecoration(
                         errorText: "Enter valid email"),
                     );
                    });
                  },

您可以通过声明 String invalidEmailError 并将其设置在 TextFielderrorText 属性上来解决此问题。稍后更新此字符串以获得所需的结果。

TextField(
      decoration: InputDecoration(
      hintText: "Enter Email Id",
          errorText: invalidEmailError,
          border: OutlineInputBorder()),
          onChanged: (String value) {
          emailId = value;
        setState(() {
            isEmail(value)
                ? invalidEmailError = null
                : invalidEmailError = "Enter valid email";
        });
      },
      )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2010-12-18
    • 2019-07-03
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多