0

I am working on Flutter TextFormField. and i want to display an error message below the TextFormField but when i debug i got this error

The method 'validate' was called on null. Receiver: null Tried calling: 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'); } 

1 Answer 1

1

in order to use the validate function, your Column should be wrap in 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; }, ) ]))), 
Sign up to request clarification or add additional context in comments.

1 Comment

thanx, that worked for me just fine, but the problem is that it's still adding the empty fields to the list, Any idea of how to fix that?