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?
uj5u.com熱心網友回復:
是的,您可以制作如下所示的自定義表單欄位。
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,
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459938.html
上一篇:如何去除前導0并將剩余值除以100,在C#中的整數和小數部分之間使用點分隔符
下一篇:應用欄上的InkWell高度飛濺
