skip to Main Content

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"))

3

Answers


  1. 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.
    )
    
    Login or Signup to reply.
  2. 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"),
      ),
    ),
        
    
    Login or Signup to reply.
  3. 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"),
      ),
    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search