Home > other >  Exception has occurred. _CastError (Null check operator used on a null value)
Exception has occurred. _CastError (Null check operator used on a null value)

Time:01-04

How is Null Safety in this code

class EditProduct extends StatelessWidget {
  final _formKey = GlobalKey<FormState>();

The line of code with the problem: _formKey.currentState!.validate()

ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      updateProduct().then((value) {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => HomePage()));
                      });
                    }
                  },
                  child: Text("save"))

CodePudding user response:

to use form key you need to add the Form widget and into that widget, you need to pass formKey in the property key like this :

Form(
  key: _formKey,
  child // your textfields.
)

CodePudding user response:

Try the following code:

Form(
  key: _formKey,
  child ElevatedButton(
    onPressed: () {
      if (_formKey.currentState!.validate()) {
        updateProduct().then((value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage()));
            },
         );
      }
    },
    child: Text("save"),
  ),
),

CodePudding user response:

Have you assigned _formkey inside the form widget?

    Form(
       key: _formKey,
       child : ElevatedButton(
    onPressed: () {
      if (_formKey.currentState!.validate()) {
        updateProduct().then((value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage()));
            },
         );
      }
    },
    child: Text("save"),
  ),
),
    
  • Related