我如何检查TextFormField的文本是否为空?我有这个示例代码。
TextFormField(
controller: firstNameController,
style: TextStyle(color: Color.fromRGBO(136, 136, 136, 1)),
decoration: InputDecoration(
border: UnderlineInputBorder(borderSide: BorderSide()),
hintStyle: TextStyle(color: Colors.grey.shade300),
hintText: sharedPreferences.getString("firstName")
),
onChanged: (String value){
final trimValue = value.trim();
if(value != trimValue){
setState(() {
if(trimValue != ""){
firstNameController.text = trimValue;
}else{
firstNameController.text = sharedPreferences.getString("firstName");
}
});
}
},
),
我试着用 if(trimValue != "")
语句,但在运行这个部件后,我的控制台扔给我。
I/flutter (20342): UsageError: Cannot perform update with the provided values.
I/flutter (20342): Details:
I/flutter (20342): Could not use specified `lastName`. Cannot set "" (empty string) for a required attribute.
我想让它检查是否给定了一个字符串,如果给定了,他就从控制器中获取文本,如果没有,他就从shardPreferences发送文本。
有谁能解决这个问题?
你所做的事情是没有意义的,因为你要做的是对照自身进行检查。firstNameController.text/trimValue
的 firstNameController.text 是 的 价值 属性的onChanged()属性。如果你要使用 TextEditingController
.
我的建议是实际使用 addListener()
方法来检查变化。
final firstNameController = TextEditingController();
@override
void initState() {
super.initState();
firstNameController.addListener(_checkIfFieldIsEmpty);
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _checkIfFieldIsEmpty listener.
firstNameController.dispose();
super.dispose();
}
_checkIfFieldIsEmpty() {
if (firstNameController.text.trim().isEmpty) {
firstNameController.text = sharedPreferences.getString("firstName");
}
}