Sagitti Sage
Sagitti Sage

Reputation: 13

Flutter: Form Validation not checking for null input, "undefined name _formKey"

This is my current code. The "Field required" does not show up when the input is null.

class _HomeState extends State<Home> {
  final _formkey = GlobalKey<FormState>();
  final FocusNode _nameFocusNode = FocusNode();

  final TextEditingController _nameController = TextEditingController();

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        //padding: const EdgeInsets.all(15.0),
        key: _formkey,
        child: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(20.0)
),
              ),
            ),
            TextFormField(
              keyboardType: TextInputType.name,
              textInputAction: TextInputAction.next,
              focusNode: _nameFocusNode,
              onFieldSubmitted: (String value) {
                _nextFocus(_addressFocusNode);
              },
              controller: _nameController,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Field required';
                }
                return null;
              },

And this is the submit button code:

       ElevatedButton(
              style: ButtonStyle(
                backgroundColor:
                    MaterialStateProperty.all<Color>(Colors.deepOrange),
              ),
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) {
                    return AlertDialog(
                      content: SingleChildScrollView(
                          child: ListBody(
                        children: [
                          Text(
                            'Name:',
                            style: TextStyle(
                              fontSize: 17,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(_nameController.text),
                          ),
                            onPressed: () => Navigator.pop(context, 'Confirm'),
                            child: const Text('Confirm'),
                          ),
                        ],
                      )),
                    );
                  },
                );
              },
              child: Text('Submit'),
            ),

Furthermore, according to flutter docs (https://docs.flutter.dev/cookbook/forms/validation), I'm sure I have to insert this portion of code on my submit button but I can't find the right way to integrate it.

onPressed: () {
                // Validate returns true if the form is valid, or false otherwise.
                if (_formKey.currentState!.validate()) {
                }

I've inserted the

if (_formKey.currentState!.validate())

after "onPressed" and before "showDialog" but I get the error "Undefined name '_formKey'"

Upvotes: 0

Views: 835

Answers (1)

EdwynZN
EdwynZN

Reputation: 5601

You need to wrap your widget with a Form and pass your key to that widget (because you want a FormState from that GloabaaKey)

return Form(
  key: _formKey,
  child: Scaffold(...),
);

That way your GlobalKey will actually reference a FormState and you can pass that to any onPressed method

onPressed: () {
     // Validate returns true if the form is valid, or false otherwise.
     if (_formKey.currentState!.validate()) {
         showDialod(...);
     } else {
       /// show error message or do something
     }

Upvotes: 1

Related Questions