flutter _formKey.currentState==null 报错 Null check operator used on a null value
flutter _formKey.currentState==null报错 Null check operator used on a null value
·
flutter 组件 Form 需要设置其 key ,通过 key 获取当前的 FormState 来验证表单
但有时候会出现 FormState 为空,即 _formKey.currentState == null 的情况
以下是 FormState 可能会出现 null 的2种情况,
1 . 组件被移除了
2 . 组件不是 StatefulWidget 或者 State对象不是“T”的子类型
我遇到的问题:
ListView(
children: [
Form(
key: _formKey,
child: TextFormField(
validator: (val) => (val == null || val.isEmpty)
? S.current.check
: null,
decoration: InputDecoration(),
),
),
......
],
),
_formKey.currentState!.validate() //error: Null check operator used on a null value
}
因为外面用的是 ListView 组件,当数据够多,上下滑动, 当Form 组件超出了 ListView 的预加载区域 ,Form组件被移除,FormState 就为空了
可以把 ListView 改成可滑动的 Column
SingleChildScrollView(
child: Column(
children: [
ListTile(
......
更多推荐
已为社区贡献9条内容
所有评论(0)