首页 > 解决方案 > value.isEmpty 在我尝试编译代码时抛出错误

问题描述

 TextFormField(
                        obscureText: true,
                        decoration: InputDecoration(
                          hintText: "Enter password",
                          labelText: "Password",
                        ),
                        validator: (value) {
                          if (value.isEmpty) {
                            return "Password can't be empty";
                          }
                          null;
                        },
                      ),

我正在看一个关于颤振的教程,我知道它太基础了,但似乎无法修复这个错误但不适合我,我还不明白它显示The property 'isEmpty' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!'). 这个错误

标签: flutterdart

解决方案


这是因为valueis 类型String?并且可以为 null。在你的情况下,你必须检查 if valueis null

 TextFormField(
                        obscureText: true,
                        decoration: InputDecoration(
                          hintText: "Enter password",
                          labelText: "Password",
                        ),
                        validator: (String? value) {
                          if (value!.isEmpty) {
                            return "Password can't be empty";
                          }
                          null;
                        },
                      ),

推荐阅读