Home > Enterprise >  Exception while trying to validate a TextFormField Input
Exception while trying to validate a TextFormField Input

Time:12-21

I am trying to validate two TextFormFields (Email and Password) in my project. But i get an exception while to validate the TextFormField. Can someone let me know where i went wrong? Or how the error can be fixed.

The error i get is : ════════ Exception caught by gesture ═══════════════════════════════════════════ Null check operator used on a null value ════════════════════════════════════════════════════════════════════════════════

My Code :

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();

    TextEditingController emailController;
    TextEditingController passwordController;
    final authService = Provider.of<AuthService>(context);
    emailController = TextEditingController();
    passwordController = TextEditingController();
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
          child: Column(children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(top: 60.0),
          child: Center(
            child: Container(
                width: 300,
                height: 380,
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(50.0)),
                child: Image.asset(
                  'assets/images/logo.png',
                )),
          ),
        ),
        const SizedBox(height: 15.0),
        Padding(
          padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 0, bottom: 0),
          child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter the email.';
              }
              return null;
            },
            controller: emailController,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(60),
                ),
                prefixIcon: const Icon(Icons.mail),
                labelText: 'E-Mail',
                hintText: '[email protected]'),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 15, bottom: 0),
          child: TextFormField(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter the password.';
              }
              return null;
            },
            controller: passwordController,
            obscureText: true,
            decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(60),
                ),
                prefixIcon: const Icon(Icons.vpn_key),
                labelText: 'Password',
                hintText: 'Enter your Password'),
          ),
        ),
        const SizedBox(
          height: 100,
        ),
        TextButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Processing')),
                );
              }
              authService.signInWithEmailAndPassword(context,
                  emailController.text.trim(), passwordController.text.trim());
            },
            child: const Text(
              'Login',
              textAlign: TextAlign.center,
            )),
        MaterialButton(
            onPressed: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => forgotPassword()));
            },
            child: Text(
              'Forgot Password',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 13.0, color: Colors.red.shade900),
            ))
      ])),
    );
  }
}

Thank you in advance.

CodePudding user response:

There is no Form widget used _formKey in your snippet, that's why it is throwing errors from _formKey.currentState!.validate(). Because you are using ! that says currentState of formKey will never get null.

You can do handle it by check null state first.

 TextButton(
             onPressed: () {
               if (_formKey.currentState == null) {
                 return; // dont execute rest code
               }
               if (_formKey.currentState!.validate()) {
                 ScaffoldMessenger.of(context).showSnackBar(
                   const SnackBar(content: Text('Processing')),
                 );
               authService.signInWithEmailAndPassword(context, 
              emailController.text.trim(),
               passwordController.text.trim());
               },

Place Form widget before Column widget.

   body: SingleChildScrollView(
          child: Form(
        key: _formKey,
        child: Column(children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 60.0),
            child: Center(

More about forms validation

CodePudding user response:

You are causing this error because you have defined a _formkey but not used it in your code so it doesn't have any value or State right now you have to wrap your TextFormField in Form widget and need to pass the defined key, you can check in the code below

final _formKey = GlobalKey<FormState>();

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {

    TextEditingController emailController;
    TextEditingController passwordController;
    final authService = Provider.of<AuthService>(context);
    emailController = TextEditingController();
    passwordController = TextEditingController();
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
          child: Column(children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 60.0),
              child: Center(
                child: Container(
                    width: 300,
                    height: 380,
                    decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(50.0)),
                    child: Image.asset(
                      'assets/images/logo.png',
                    )),
              ),
            ),
            const SizedBox(height: 15.0),
            Form(
              key: _formKey,
              child: Padding(
                padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 0, bottom: 0),
                child: TextFormField(
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter the email.';
                    }
                    return null;
                  },
                  controller: emailController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(60),
                      ),
                      prefixIcon: const Icon(Icons.mail),
                      labelText: 'E-Mail',
                      hintText: '[email protected]'),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 25.0, right: 25.0, top: 15, bottom: 0),
              child: TextFormField(
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter the password.';
                  }
                  return null;
                },
                controller: passwordController,
                obscureText: true,
                decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(60),
                    ),
                    prefixIcon: const Icon(Icons.vpn_key),
                    labelText: 'Password',
                    hintText: 'Enter your Password'),
              ),
            ),
            const SizedBox(
              height: 100,
            ),
            TextButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Processing')),
                    );
                  }
                  authService.signInWithEmailAndPassword(context,
                      emailController.text.trim(), passwordController.text.trim());
                },
                child: const Text(
                  'Login',
                  textAlign: TextAlign.center,
                )),
            MaterialButton(
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => forgotPassword()));
                },
                child: Text(
                  'Forgot Password',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 13.0, color: Colors.red.shade900),
                ))
          ])),
    );
  }
}
  • Related