skip to Main Content

I’m trying to call a widget when a form is validated. However, I’m running in a bit of problem here

In my code

  final GlobalKey<FormState> formkey = GlobalKey<FormState>();

Then later

formkey.currentState!.validate() 
                      ? const SizedBox()///this is not the actual widget but just an example to simplify things
                      : Container()

Whenever I bring the ! as in formkey.currentState!.validate() and run the app, I get an error on my phone that Null check operator used on a null value. When I remove it and put ? as in formkey.currentState?.validate() I get an error in the code with the message

A nullable expression can’t be used as a condition.
Try checking that the value isn’t ‘null’ before using it as a condition

What should I do?

By the way, this is after I’ve used the validation logic in a TextFormField wrapped in a Form widget.

2

Answers


  1. just add null aware (??) condition to handle the case when formKey is null.

    (formkey.currentState?.validate() ?? false)
                          ? const SizedBox()
                          : Container()
    

    Full Example Code:

    class TestCase extends StatefulWidget {
      const TestCase({super.key});
    
      @override
      State<TestCase> createState() => _TestCaseState();
    }
    
    class _TestCaseState extends State<TestCase> {
      final formKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Form(
            key: formKey,
            child: Column(
              children: [
                (formKey.currentState?.validate() ?? false)
                    ? const Text("Valid")
                    : const Text("Invalid"),
                TextFormField(
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter some text';
                    }
    
                    return null;
                  },
                ),
                MaterialButton(
                  onPressed: () {
                    setState(() {});
                  },
                  child: const Text("Submit"),
                )
              ],
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Add the key to the scaffold?

    Widget build(BuildContext context) {
        return Scaffold(
            key: formkey,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search