user12674982
user12674982

Reputation:

TextFormField validation in Flutter

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');
               }

Upvotes: 0

Views: 279

Answers (1)

Bhargav Sejpal
Bhargav Sejpal

Reputation: 1618

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;
                              },
               )
              ]))),

Upvotes: 1

Related Questions