Home > Back-end >  Validation event for custom widget
Validation event for custom widget

Time:10-12

In flutter, a TextFormField for an example, has a validator which can be used for validation:

 TextFormField(validator: validator ...
    

Then in your form, you can call validate on the Form widget to make all children with these validators validate:

_formKey.currentState!.validate()

If a validation fails, the TextFormField will display an error text along with a position and color transition.

I have my own custom photo widget, and I would like to make it able to support the same validation functionality. That is, give it a validator, hook it up to the validate() event, and if the user hasn´t added any photo, the validation fails and shows the error text the validator returns. But I cannot figure out how to implement the validate eventlistener on a custom widget. So how would you go around this?

CodePudding user response:

There are three ways to accomplish this

  1. State management which will be complicated for this scenario

  2. SetState() which will update your whole UI and will be expensive

  3. ValueNotifier and ValueListableBuilder which I recommend

First define a valuenotifier

late ValueNotifier<bool> _isValid;

Then in initState initialize it and add a listener to it which will be your validator

...
_isValid = ValueNotifier(true);
_isValid.addListener((){
    If(){ //your validation
        _isValid.value = true;
    } else {
        _isValid.value = false;
    }
})

Then in your UI add ValueListableBuilder and put your widget inside it to listen to its changes and change accordingly

ValueListableBuilder(
    listenableValue: _isValid,
    builder: (context, bool yourValue, child){
        // return your widget and use yourValue to update your UI
 }
)

Sorry if there is any misspelling. I wrote it on my mobile

CodePudding user response:

Inherit a custom widget from FormField. Each individual form field should be wrapped in a FormField widget like TextFormField.

Form(
  key: _formKey,
  child: Column(
    children: <Widget>[
      TextFormField(
        validator: (String? value) {
          if (value == null || value.isEmpty) {
            return 'Please enter some text';
          }
          return null;
        },
      ),
      CustomFormField(
        validator: (String? value) {
          if (value == null || value.isEmpty) {
            return 'Please select something';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {}
        },
        child: const Text('Submit'),
      ),
    ],
  ),
);
  • Related