您可以创建自己的FormField:
class TakePictureFormField extends FormField<String> {
/// Creates a [FormField] that contains an [ElevatedButton] to take a picture
/// with the phone camera.
///
/// The [String] value corresponds to the path of the picture taken.
TakePictureFormField({
Key? key,
String? initialValue,
FormFieldSetter<String>? onSaved,
FormFieldValidator<String>? validator,
bool enabled = true,
AutovalidateMode? autovalidateMode,
ButtonStyle? buttonStyle,
void Function(String)? onChanged,
}) : super(
key: key,
initialValue: initialValue,
onSaved: onSaved,
validator: validator,
enabled: enabled,
autovalidateMode: autovalidateMode,
builder: (FormFieldState<String> field) {
final currentValue = field.value;
return InputDecorator(
decoration: InputDecoration(
border: InputBorder.none,
errorText: field.errorText,
errorBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(field.context).errorColor,
),
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
style: buttonStyle,
onPressed: () async {
// Fake implementation to take a picture.
final value = await Future<String>.delayed(
const Duration(microseconds: 300),
() => 'my_path/to/image');
field.didChange(value);
if (onChanged != null) {
onChanged(value);
}
},
child: const Text('Take a Picture'),
),
if (currentValue != null) Text(currentValue),
],
),
);
},
);
}
然后在 Form 中使用它,就像对任何其他 FormField 小部件一样:
TakePictureFormField(
validator: (val) =>
val == null || val.isEmpty ? 'Error invalid picture' : null,
)
Try the complete example on DartPad