[英]TextFormField validation in Flutter
我正在研究 Flutter TextFormField
。 我想在TextFormField
下方显示一条错误消息,但是当我调试时出现此错误
在 null 上调用了“验证”方法。 接收方:null 尝试调用:validate()
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController _titleController;
TextEditingController _descriptionController;
final _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
_titleController = new TextEditingController(text: widget.products.adTitle);
_descriptionController = new TextEditingController(text: widget.products.description); @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Products")
),
body: Container(
margin: EdgeInsets.all(15.0),
alignment: Alignment.center,
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: _titleController,
decoration: InputDecoration(labelText: 'Title'),
validator: (text) {
if (text == null || text.isEmpty) {
return 'Text is empty';
}
return null;
},
RaisedButton(
child: (widget.products.id != null)? Text('Update') : Text('Add'),
onPressed:(){
if (_formKey.currentState.validate()) {
child: Text('Submit');
}
为了使用验证 function,您的列应包装在表单中
Container(
margin: EdgeInsets.all(15.0),
alignment: Alignment.center,
child: Form(
key: _formKey,
child: Column(children: <Widget>[
TextFormField(
controller: _titleController,
decoration:InputDecoration(labelText: 'Title'),
validator: (text) {
if (text == null || text.isEmpty) {
return 'Text is empty';
}
return null;
},
)
]))),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.