我正在研究Flutter TextFormField
。我想在TextFormField
下面显示一条错误消息,但是当我调试时出现此错误
在null上调用了方法'validate'。 接收者: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');
}
答案 0 :(得分:1)
为了使用validate函数,您的Column应该换成Form
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;
},
)
]))),