【问题标题】:Flutter - Text Editing controller empty, but Flutter thinks there's a value present?Flutter - 文本编辑控制器为空,但 Flutter 认为存在价值?
【发布时间】:2021-05-17 02:59:02
【问题描述】:

我正在尝试在我的网络应用中实现“忘记密码”功能。

我有一个电子邮件文本编辑控制器作为输入字段和一个提升按钮,该按钮最终会将值推送到我的忘记密码功能。

为了处理错误,我尝试实现一个 if 语句以确保如果文本字段为空,则不会发送请求。

然而,在测试块时,Flutter 似乎认为文本字段中有一个值,而我实际上没有输入任何内容?有人可以解释我要去哪里错了吗?谢谢。这是我的代码:

  class ForgotPasswordScreen extends StatelessWidget {
  final TextEditingController forgotPasswordController =
      TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Forgot Password'),
        ),
        body: Center(
          child: Container(
            width: MediaQuery.of(context).size.width * 0.5,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextFormField(
                  controller: forgotPasswordController,
                  decoration: InputDecoration(
                      hintStyle: TextStyle(color: Colors.grey),
                      border: OutlineInputBorder()),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ElevatedButton(
                      onPressed: () {
                        try {
                          if (forgotPasswordController.value != null) {
                            print('Success');
                          } else {
                            print("fail");
                          }
                        } catch (e) {
                          print(e);
                        }
                      },
                      child: Text('Send reset link')),
                )
              ],
            ),
          ),
        ));
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    TextEditingController 的默认值为空,而不是 null

    .value 不是字符串。这是TextEditingValue 的实例,它不为空。这就是为什么它转到else。在.text 上使用.isEmpty,因为它返回字符串。

    if (forgotPasswordController.text.isNotEmpty) {
       // pass
    } else {
       // fail
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 2020-04-15
      • 2019-12-25
      • 1970-01-01
      • 2021-02-24
      • 2021-07-07
      • 1970-01-01
      • 2020-08-13
      相关资源
      最近更新 更多