flutter - 我的 TextFormField 的验证总是抛出一个错误
问题描述
child: TextFormField(
controller: emailcontroller,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle:
TextStyle(color: Colors.grey[400])),
keyboardType: TextInputType.emailAddress,
validator: (String value) { <= this line throw error
if (value.isEmpty) {
return 'Please Enter Name';
}
return null;
},
onSaved: (String value) { <= this line throw error
name = value;
},
)
“验证器:(字符串值)”抛出:
参数类型 'void Function(String)' 不能分配给参数类型 'void Function(String?)?'.dartargument_type_not_assignable
“onSaved:(字符串值)”抛出:
参数类型 'void Function(String)' 不能分配给参数类型 'void Function(String?)?'.dartargument_type_not_assignable
当我检查 GitHub 代码时,我看到了相同的结构,但它没有抛出错误
child: TextFormField(
keyboardType: TextInputType.text,
decoration: buildInputDecoration(Icons.person, "Full Name"),
validator: (String value) {
if (value.isEmpty) {
return 'Please Enter Name';
}
return null;
},
onSaved: (String value) {
name = value;
},
),
“buildInputDecoration”功能:
InputDecoration buildInputDecoration(IconData icons,String hinttext) {
return InputDecoration(
hintText: hinttext,
prefixIcon: Icon(icons),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.green,
width: 1.5
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.blue,
width: 1.5,
),
),
enabledBorder:OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.blue,
width: 1.5,
),
),
);
}
解决方案
您来自 GitHub 的示例适用于没有 null 安全性的较旧版本的 Dart。您正在使用具有 null 安全性的 Dart,String
其类型与String?
. 所以只需将?
after添加String
到验证器函数参数:
return TextFormField(
...
validator: (String? value) {
if (value?.isEmpty ?? true) {
return 'Please Enter Name';
}
return null;
},
onSaved: (String? value) {
name = value;
},
);
您也可以只删除显式value
类型:
return TextFormField(
...
validator: (value) {
if (value?.isEmpty ?? true) {
return 'Please Enter Name';
}
return null;
},
onSaved: (value) {
name = value;
},
);
推荐阅读
- javascript - 如何使用 JavaScript 在 iframe 中插入图片?
- python - 如何使用步进函数在我的亚马逊 ec2 机器上一个接一个地运行 3 个 python 脚本?
- ruby-on-rails - 无需刷新页面即可将用户添加到可操作频道。
- mongodb - 用户不是构造函数
- sql - 最小化相同子查询的使用
- android - 无法将 Firebase 存储映像存储到文件夹中
- ubuntu - .net core web api访问容器中的文件夹
- android - 电报api配置项目异常
- python - TensorBoard 记录统计数据与训练分开
- javascript - 从子窗口调用父窗口函数不起作用