我有一個Flutter表單,其中有許多下拉式欄位和文本欄位部件,使用validate:方法驗證這些部件是很容易的。對可視欄位的驗證是顯而易見的。
然而,在許多表單中,非可見元素可能需要被驗證。例如,如果在表單中拍照,只有一個拍照的按鈕,它將把生成的檔案名輸入到一個 String var 中。 在這種情況下,我需要驗證 String var,并將驗證結果回傳給按鈕(即在按鈕下方顯示一個 "必填欄位"),但當然 String var 并不在任何 formfield widget 中持有。
既然如此,我如何才能將按鈕 "包裹 "在一個包含驗證器:方法的部件中,或者我如何將驗證器添加到按鈕本身,然后在 UI 中向用戶顯示適當的驗證資訊?
謝謝你!
uj5u.com熱心網友回復:
你可以創建你自己的FormField:
class TakePictureFormField extends FormField< String> {
//創建一個[FormField],其中包含一個[ElevatedButton]來拍攝照片。
//用手機攝像頭。
//
// [String]值對應于拍攝照片的路徑。
TakePictureFormField({
key? key。
String? initialValue,
FormFieldSetter<String> ? onSaved。
FormFieldValidator<String>? validator。
bool enabled = true,
AutovalidateMode? autovalidateMode。
ButtonStyle? buttonStyle。
void Function(String)? onChanged,
}) : super(
鍵:鍵。
initialValue: initialValue,
onSaved: onSaved,
驗證器:驗證器。
enabled: enabled,
autovalidateMode: autovalidateMode。
構建者。(FormFieldState<String> field) {
final currentValue = field.value。
return InputDecorator(
裝飾。輸入裝飾(InputDecoration)
邊框。InputBorder.none,
errorText: field.errorText,
errorBorder: 概要輸入邊框(
borderSide: borderSide(
color: Theme.of(field.context).errorColor,
),
),
),
孩子。列(
mainAxisSize: MainAxisSize.min,
兒童。[
提升的按鈕(
style: buttonStyle,
onPressed: () async {
//假的實作來拍攝照片。
final value = await Future<String> .delayed(
const Duration(microseconds: 300)。
() => 'my_path/to/image') 。
field.didChange(value)。
if (onChanged != null) {
onChanged(value)。
}
},
孩子。const Text('Take a picture')。
),
if (currentValue != null) Text(currentValue)。
],
),
);
},
);
}
然后在Form中使用它,就像你對其他FormField部件一樣:
TakePictureFormField(
驗證器。(val) =>
val == null || val.isEmpty ? 'Error invalid picture' : null,
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311782.html
標籤:
