我可以在自定义小部件的文本字段中制作验证器吗?

can I make validators like in textfield in my custom widget?

   TextFormField(
      validator: validator,
   ),

在文本字段中,有一个名为 validator 的 属性,可与 Form 小部件一起使用以显示错误。我需要在我的自定义小部件中制作一个验证器,它也可以在 Form 小部件内工作。怎么做?

假设我的自定义小部件如下所示:

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,
    );
  }
}

如何让我自己的验证器在可以在 Form 小部件内工作的绿色容器下方显示错误?

是的,您可以制作如下所示的自定义表单域。

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()
          ],
        );
      }
  );

使用

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