我试图在验证表单时调用小部件。但是,我在这里遇到了一些问题
在我的代码中
final GlobalKey<FormState> formkey = GlobalKey<FormState>();
Then later
formkey.currentState!.validate()
? const SizedBox()///this is not the actual widget but just an example to simplify things
: Container()
每当我像
!
中那样携带 formkey.currentState!.validate()
并运行该应用程序时,我的手机上就会出现错误 Null check operator used on a null value
。当我删除它并像 ?
中那样放置 formkey.currentState?.validate()
时,我在代码中收到错误消息 A nullable expression can't be used as a condition. Try checking that the value isn't 'null' before using it as a condition
。
我该怎么办?
顺便说一下,这是在我使用了包含在 Form 小部件中的 TextFormField 中的验证逻辑之后的结果。
只需添加 null 感知 (??) 条件来处理 formKey 为 null 的情况。
(formkey.currentState.validate() ?? false)
? const SizedBox()
: Container()