Flutter error, Null check operator used on a null value

Issue

Whenever I tried to do register and tap on the register button then I am having this type of problem with the null check operator used on null values.
I get this error message

══════ Exception caught by gesture ════════════════════

The following _CastError was thrown while handling a gesture:
Null check operator used on a null value

When the exception was thrown, this was the stack

#0 _AuthorizationState.build.
package:gr_space/screens/profile_screen.dart:244

#1 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:989

#2 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182

#3 TapGestureRecognizer.handleTapUp

package:flutter/…/gestures/tap.dart:607

#4 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:296


Handler: "onTap"
Recognizer: TapGestureRecognizer#f8d29
debugOwner: GestureDetector
state: ready
won arena
finalPosition: Offset(215.0, 716.5)
finalLocalPosition: Offset(199.0, 16.0)
button: 1
sent tap down
═════════════════════════════════════════════════════════

this is my auth screen. dart file

import 'package:flutter/material.dart';

enum AuthMode { Signup, Login }

class ProfileScreen extends StatelessWidget {
  static const routeName = '/profile';
  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      child: Authorization(),
    );
  }
}

class Authorization extends StatefulWidget {
  @override
  _AuthorizationState createState() => _AuthorizationState();
}

class _AuthorizationState extends State<Authorization> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  AuthMode _authMode = AuthMode.Login;
  final _passwordController = TextEditingController();
  Map<String, String> _authData = {
    'firstName': '',
    'lastName': '',
    'username': '',
    'email': '',
    'phoneNumber': '',
    'dateOfBirth': '',
    'password': '',
    'confirmPassword': '',
    'city': '',
    'gender': '',
  };
  void _switchAuthMode() {
    if (_authMode == AuthMode.Login) {
      setState(() {
        _authMode = AuthMode.Signup;
      });
    } else {
      setState(() {
        _authMode = AuthMode.Login;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;

    return Container(
      height: _authMode == AuthMode.Signup ? 320 : 260,
      constraints:
          BoxConstraints(minHeight: _authMode == AuthMode.Signup ? 620 : 660),
      width: deviceSize.width,
      padding: EdgeInsets.all(16.0),
      child: Form(
        child: SingleChildScrollView(
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(labelText: 'First name'),
                keyboardType: TextInputType.name,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['firstName'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Last name'),
                keyboardType: TextInputType.emailAddress,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['lastName'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Username'),
                keyboardType: TextInputType.name,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty) {
                    return 'Required';
                  }
                },
                onSaved: (value) {
                  _authData['username'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'E-Mail'),
                keyboardType: TextInputType.emailAddress,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty || !value.contains('@')) {
                    return 'Invalid email!';
                  }
                },
                onSaved: (value) {
                  _authData['email'] = value!;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                controller: _passwordController,
                // ignore: missing_return
                validator: (value) {
                  if (value!.isEmpty || value.length < 5) {
                    return 'Password is too short!';
                  }
                },
                onSaved: (value) {
                  _authData['password'] = value!;
                },
              ),
              (_authMode == AuthMode.Login)
                  ? Container(
                      child: Column(children: [
                        TextFormField(
                          enabled: _authMode == AuthMode.Signup,
                          decoration:
                              InputDecoration(labelText: 'Confirm Password'),
                          obscureText: true,
                          validator: _authMode == AuthMode.Signup
                              // ignore: missing_return
                              ? (value) {
                                  if (value != _passwordController.text) {
                                    return 'Passwords do not match!';
                                  }
                                }
                              : null,
                          onSaved: (value) {
                            _authData['confirmPassword'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration:
                              InputDecoration(labelText: 'Phone Number'),
                          keyboardType: TextInputType.phone,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty || value.length < 7) {
                              return 'Invalid phone number!';
                            }
                          },
                          onSaved: (value) {
                            _authData['phone number'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: 'City'),
                          keyboardType: TextInputType.emailAddress,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty) {
                              return 'Required';
                            }
                          },
                          onSaved: (value) {
                            _authData['city'] = value!;
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: 'Gender'),
                          keyboardType: TextInputType.emailAddress,
                          // ignore: missing_return
                          validator: (value) {
                            if (value!.isEmpty) {
                              return 'Required';
                            }
                          },
                          onSaved: (value) {
                            _authData['gender'] = value!;
                          },
                        ),
                      ]),
                    )
                  : SizedBox(
                      height: 10,
                    ),
              SizedBox(
                height: 20,
              ),
              MaterialButton(
                height: 40,
                color: Theme.of(context).primaryColor,
                minWidth: double.infinity,
                onPressed: () {
                  if(_formKey.currentState!.validate()){
                    print('yess');
                  }
                },
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Text(
                  'Register',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
              Divider(
                color: Colors.black,
              ),
              MaterialButton(
                height: 40,
                color: Color.fromARGB(255, 222, 82, 69),
                minWidth: double.infinity,
                onPressed: () {},
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/gmail_logo.png',
                      height: 25,
                      width: 25,
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    Text(
                      'Register with gmail',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              MaterialButton(
                height: 40,
                color: Color.fromARGB(255, 65, 103, 178),
                minWidth: double.infinity,
                onPressed: () {},
                elevation: 0,
                //shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/facebook_logo.png',
                      height: 25,
                      width: 25,
                    ),
                    SizedBox(
                      width: 15,
                    ),
                    Text(
                      'Register with Facebook',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: 20,
              ),
              Text(
                'Already have an account?',
              ),
              SizedBox(
                height: 10,
              ),
              TextButton(
                onPressed: _switchAuthMode,
                child: Text(
                  'Sign In',
                  style: TextStyle(
                    color: Colors.blue,
                    decoration: TextDecoration.underline,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Solution

It’s because _formKey.currentState is never assigned – in order for it to be assigned, you need to pass the key to your Form widget, like so:

Form(
  key: _formKey,
  child: ...
)

The Form widget will then take care of assigning currentState.

It would also be a good idea to check the form state in a way that won’t necessarily crash your app if _formKey.currentState is null. For example, in your Register button:

onPressed: () {
  if (_formKey.currentState == null) {
    print("_formKey.currentState is null!");
  } else if (_formKey.currentState!.validate()) {
    print("Form input is valid");
  }
}

Answered By – Michael Horn

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *