0

I'm trying to save the form on a button click but it is giving me an error that the "method can not be called because the receiver can be null". I'm providing a null check but the error is not getting solved. Any help would be greatly appreciated.

Here is the code

onPressed: () {
    if (_formKey.currentState != null) {
        _formKey.currentState.save(); // this gives the error
    }
},

This onPressed is linked with the elevated button and the _formKey here is this:

// key to work with the form
final _formKey = GlobalKey<FormState>();
dipansh
  • 331
  • 3
  • 15

1 Answers1

2

Since you are checking that currentState is not null you can use the ! to fix your problem.

onPressed: () {
    if (_formKey.currentState != null) {
        _formKey.currentState!.save();
    }
},

Another way to fix this is to create a variable which stores the currentState.

onPressed: () {
    final state = _formKey.currentState;
    if (state != null) {
        state.save();
    }
},
quoci
  • 2,940
  • 1
  • 9
  • 21