flutterflutter-form-builderflutter-textinputfield

Error: Method 'save' cannot be called on 'FormState?' because it is potentially null


Flutter form saved error Have a formKey but I'm still getting an error

This my code

class _TextFormFieldsState extends State<TextFormFields> {
  String _name = "";

  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(    
          primaryColor: Colors.red,
          accentColor: Colors.purpleAccent,
          errorColor: Colors.black
      ),
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.save),
        ),
        appBar: AppBar(
          title: Text("Text Form Field"),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          child: Form(
            key: formKey,
            autovalidateMode: AutovalidateMode.always,
            child: ListView(
              children: [
                TextFormField(
                  decoration: InputDecoration(
                    prefixIcon: Icon(Icons.account_circle),
                    hintText: "Your Name",
                    labelText: "FullName",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter some text';
                    }
                    return null;
                  },
                  onSaved: (String? value) {
                    _name = value.toString();
                  },
                ),
                ElevatedButton(
                  onPressed: () {
                    // Validate returns true if the form is valid, or false otherwise.
                    if (formKey.currentState!.validate()) {
                      formKey.currentState.save();
                      debugPrint("Girilen ad $_name");
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Solution

  • This is due to Dart's flow analysis.

    Your formKey is an instance variable and thus it cannot be detected by flow analysis that it is definitely not null even after your if check.

    Use it like this instead formKey.currentState!.save();