Flutter - 文本编辑控制器为空,但 Flutter 认为存在值?

TJM*_*h95 3 dart flutter

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

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

为了处理错误,我尝试实现 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')),
                )
              ],
            ),
          ),
        ));
  }
}
Run Code Online (Sandbox Code Playgroud)

Tir*_*tel 13

默认情况下 的值为TextEditingController空,而不是null.

.value不是字符串。它是TextEditingValue的实例,它不为空。这就是为什么它会去else。使用.isEmptyon.text因为它返回 String。

if (forgotPasswordController.text.isNotEmpty) {
   // pass
} else {
   // fail
}
Run Code Online (Sandbox Code Playgroud)