Agu*_*ana 0 dart flutter flutter-layout
TextFormField(
validator: validator,
),
Run Code Online (Sandbox Code Playgroud)
在文本字段中,有一个名为 的属性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,
);
}
}
Run Code Online (Sandbox Code Playgroud)
如何制作我自己的验证器以在可以在Form小部件内工作的绿色容器下方显示错误?
小智 5
是的,您可以制作如下所示的自定义表单字段。
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()
],
);
}
);
Run Code Online (Sandbox Code Playgroud)
使用
CounterFormField(
autovalidate: false,
validator: (value) {
if (value < 0) {
return 'Negative values not supported';
}
},
onSaved: (value) => this._age = value,
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
517 次 |
| 最近记录: |