Home > Software design >  can I make validators like in textfield in my custom widget?
can I make validators like in textfield in my custom widget?

Time:04-21

   TextFormField(
      validator: validator,
   ),

in textfield, there is a property called validator that can be used with Form widget to show an error. I need to make a validator in my custom widget that can also work inside the Form widget. how to do that?

let say my custom widget is like below:

class MyCustomWidget extends StatelessWidget {
  const MyCustomWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 100,
      color: Colors.green,
    );
  }
}

how to make my own validator to show error below that green container that can work inside the Form widget ?

CodePudding user response:

Yes, You can make a custom form field like the below.

class CounterFormField extends FormField<int> {

  CounterFormField({
    FormFieldSetter<int> onSaved,
    FormFieldValidator<int> validator,
    int initialValue = 0,
    bool autovalidate = false
  }) : super(
      onSaved: onSaved,
      validator: validator,
      initialValue: initialValue,
      autovalidate: autovalidate,
      builder: (FormFieldState<int> state) {
        return Column(
          children: <Widget>[
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.remove),
                  onPressed: () {
                    state.didChange(state.value - 1);
                  },
                ),
                Text(
                    state.value.toString()
                ),
                IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    state.didChange(state.value   1);
                  },
                ),
              ],
            ),
            state.hasError?
            Text(
              state.errorText,
              style: TextStyle(
                  color: Colors.red
              ),
            ) :
            Container()
          ],
        );
      }
  );

Use

CounterFormField(
   autovalidate: false,
   validator: (value) {
     if (value < 0) {
       return 'Negative values not supported';
     }
    },
   onSaved: (value) => this._age = value,
)
  • Related