Ad

Exception While Trying To Validate A TextFormField Input

- 1 answer

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.

Ad

Answer

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

Ad
source: stackoverflow.com
Ad