Home > database >  Flutter Form widget not validating all fields in the form
Flutter Form widget not validating all fields in the form

Time:01-09

I have a IntlPhoneWidget and a textfield widget inside of a stepper widget. When I press the continue button it only validates the intlphonewidget and not the textfield. Also how do I put in a custom validation message for each of the fields inside of the stepper if those fields are empty?

Here is my code-

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Stepper(
          currentStep: _currentStepper,
          onStepContinue: _continueStep,
          steps: [
            Step(
              title: const Text('Enter your name and phone number'),
              content: Column(
                children: [
                  TextField(
                    controller: _displayNameTextFieldController,
                  ),
                  IntlPhoneField(
                    decoration: const InputDecoration(
                      labelText: 'Phone Number',
                    ),
                    onChanged: (phone) {
                      setState(() {
                        _phoneNumber = (phone.completeNumber).trim();
                      });
                    },
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void _continueStep() {
    if (_currentStepper == 0) {
      _formKey.currentState?.validate();
    }
  }

CodePudding user response:

This happened because the IntlPhoneField has built-in validator, but TextField doesn't, if you want to have validator for first field too , you need to use TextFormField instead and set the validator like this:

TextFormField(
    controller: _displayNameTextFieldController,
    validator: (value) {
      if (value != null &&  value.isEmpty) {
        return 'fill name field';
      }

      return null;
    },
  )
  • Related