Flutter: auto scroll to the checkbox(or any form widget) when _formKey.currentState.validate() is false

1,236

Well you can use focus node to requestFocus in the field, when it is invalid. Something like this.

First create a focus node for each field like this.

FocusNode phone = FocusNode();

Then create a validator class.

class VONPhoneValidator extends TextFieldValidator {
  final FocusNode focusNode;
  VONPhoneValidator(this.focusNode,
      {String errorText = 'Enter a valid phone number'})
      : super(errorText);

  @override
  bool get ignoreEmptyValues => true;

  @override
  bool isValid(String value) {
    if (hasMatch(r'^[0-9]{10}$', value)) {
      return true;
    } else {
      focusNode.requestFocus();
      return false;
    }
  }
}

And this is going to be your field,

TextFormField(
      maxLengthEnforced: true,
      keyboardType: TextInputType.phone,
      controller: _phoneController,
      focusNode: phone,
      validator: VONPhoneValidator(phone, errorText: "Enter Valid Phone Number"),
      decoration: InputDecoration(
        prefixIcon: CountryCodePicker(
          hideMainText: true,
          initialSelection: 'NP',
          favorite: ['NP', 'IN'],
          showCountryOnly: true,
          showFlagMain: true,
          flagWidth: 20,
          boxDecoration: BoxDecoration(color: Colors.white),
          onChanged: (value) {
            _formController.country.value = value.toString();
          },
        ),
        labelText: 'Phone Number',
        border: OutlineInputBorder(borderSide: BorderSide()),
      ),
    );
Share:
1,236
Admin
Author by

Admin

Updated on December 22, 2022

Comments

  • Admin
    Admin over 1 year

    I have one longer form and save button at bottom of form. when user taps on save button, form field validator highlights error text based on validator() function. my problem is when there is any error into form, page should be scroll to that error widget(TextFormField, Checkbox, Slider or any Custom form field).

    I tried with FocusScope.of(context).requestFocus(focus_node); but its not scrolling. I also tried with ScrollController like this,

      final RenderBox renderBoxRed = key.currentContext.findRenderObject();
      final positionRed = renderBoxRed.localToGlobal(Offset.zero);
      scrollController.animateTo(positionRed.distance, duration: Duration(milliseconds: 300), curve: Curves.easeIn);
    

    but its always scrolling to top of the screen.

    Another scenario is I have terms and condition screen where there is longer text and at the end of terms text, I added checkbox and after that again some other longer text is there. and I added button on top of screen. if user press that button before checking that terms checkbox, screen should be scroll to that checkbox to highlight checkbox so user can know that terms and condition agreement is required.

    How to achieve that with Flutter? is there any way to auto scroll to required field when form.currentState.validate() fails??