我对 Flutter 很陌生,我正在努力创建自定义表单字段。问题是我的自定义 FormField 中的验证器和 onSaved 方法都没有被调用。我真的不知道为什么当我触发 a formKey.currentState.validate()or时它们会被忽略formKey.currentState.save()。
目前这是一个非常简单的小部件,带有一个输入文本和一个按钮。该按钮将获取用户的当前位置,并使用当前地址更新文本字段。当用户在文本字段中输入地址时,它会在焦点丢失时获取该地址的位置(我也与谷歌地图集成,但我简化了它以隔离问题)。
这是我的表单字段的构造函数:
class LocationFormField extends FormField<LocationData> {
LocationFormField(
{FormFieldSetter<LocationData> onSaved,
FormFieldValidator<LocationData> validator,
LocationData initialValue,
bool autovalidate = false})
: super(
onSaved: onSaved,
validator: validator,
initialValue: initialValue,
autovalidate: autovalidate,
builder: (FormFieldState<LocationData> state) {
return state.build(state.context);
});
@override
FormFieldState<LocationData> createState() {
return _LocationFormFieldState();
}
}
Run Code Online (Sandbox Code Playgroud)
因为我需要在我的自定义 FormField 中处理状态,所以我在 FormFieldState 对象中构建它。按下按钮时更新位置状态:
class _LocationFormFieldState extends FormFieldState<LocationData> {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(
focusNode: _addressInputFocusNode,
controller: _addressInputController,
decoration: InputDecoration(labelText: 'Address'),
),
SizedBox(height: 10.0),
FlatButton(
color: Colors.deepPurpleAccent,
textColor: Colors.white,
child: Text('Locate me !'),
onPressed: _updateLocation,
),
],
);
}
void _updateLocation() async {
print('current value: ${this.value}');
final double latitude = 45.632;
final double longitude = 17.457;
final String formattedAddress = await _getAddress(latitude, longitude);
print(formattedAddress);
if (formattedAddress != null) {
final LocationData locationData = LocationData(
address: formattedAddress,
latitude: latitude,
longitude: longitude);
_addressInputController.text = locationData.address;
// save data in form
this.didChange(locationData);
print('New location: ' + locationData.toString());
print('current value: ${this.value}');
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在我的应用程序中实例化它的方式。这里没什么特别的;我把它放在一个带有表单键的表单中。还有另一个 TextFormField 来验证这个工作正常:
main.dart
Widget _buildLocationField() {
return LocationFormField(
initialValue: null,
validator: (LocationData value) {
print('validator location');
if (value.address == null || value.address.isEmpty) {
return 'No valid location found';
}
},
onSaved: (LocationData value) {
print('location saved: $value');
_formData['location'] = value;
},
); // LocationFormField
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Container(
margin: EdgeInsets.all(10.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: targetPadding / 2),
child: Column(
children: <Widget>[
_buildTitleTextField(),
SizedBox(
height: 10.0,
),
_buildLocationField(),
SizedBox(
height: 10.0,
),
_buildSubmitButton(),
],
),
),
),
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
由表单提交按钮触发的提交方法只会尝试验证然后保存表单。
只需打印保存在表单中的数据:
void _submitForm() {
print('formdata : $_formData');
if (!_formKey.currentState.validate()) {
return;
}
_formKey.currentState.save();
print('formdata : $_formData');
}
Run Code Online (Sandbox Code Playgroud)
但_formData['location']总是返回空值,并且永远不会调用验证器(日志中没有打印“验证器位置”或“保存位置”)。
我创建了一个示例 repo 来重现这个问题。您可以尝试运行该项目,首先单击“定位我”!按钮,然后是https://github.com/manumura/flutter-location-form-field 上的 Save 按钮
答案一:把build方法给Builder
替换 FormField 的构建器
builder: (FormFieldState<LocationData> state) {
return state.build(state.context);
});
Run Code Online (Sandbox Code Playgroud)
使用您的自定义构建器功能
builder: (FormFieldState<LocationData> state) {
return Column(
children: <Widget>[
TextField(
focusNode: _addressInputFocusNode,
controller: _addressInputController,
decoration: InputDecoration(labelText: 'Address'),
),
SizedBox(height: 10.0),
FlatButton(
color: Colors.deepPurpleAccent,
textColor: Colors.white,
child: Text('Locate me !'),
onPressed: _updateLocation,
),
],
});
Run Code Online (Sandbox Code Playgroud)
答案 2:伪 CustomFormFieldState
你不能扩展 FormFieldState 因为覆盖“build”函数会导致错误(解释如下)
但是,您可以创建一个将 FormFieldState 作为参数的小部件,使其成为一个单独的类,就像它扩展 FormFieldState 一样(这对我来说似乎比上面的方法更清晰)
class CustomFormField extends FormField<List<String>> {
CustomFormField({
List<String> initialValue,
FormFieldSetter<List<String>> onSaved,
FormFieldValidator<List<String>> validator,
}) : super(
autovalidate: false,
onSaved: onSaved,
validator: validator,
initialValue: initialValue ?? List(),
builder: (state) {
return CustomFormFieldState(state);
});
}
class CustomFormFieldState extends StatelessWidget {
FormFieldState<List<String>> state;
CustomFormFieldState(this.state);
@override
Widget build(BuildContext context) {
return Container(), //The Widget(s) to build your form field
}
}
Run Code Online (Sandbox Code Playgroud)
解释
扩展 FormFieldState 不起作用的原因是因为覆盖 FormFieldState 对象中的 build 方法会导致 FormFieldState 没有注册到 Form 本身。
以下是我为获得解释而遵循的功能列表
1) 你的 _LocationFormFieldState 覆盖了 build 方法,这意味着 FormFieldState 的 build 方法永远不会执行
@override
Widget build(BuildContext context)
Run Code Online (Sandbox Code Playgroud)
2)FormFieldState将自身注册到当前FormState的build方法
///function in FormFieldState
Widget build(BuildContext context) {
// Only autovalidate if the widget is also enabled
if (widget.autovalidate && widget.enabled)
_validate();
Form.of(context)?._register(this);
return widget.builder(this);
}
Run Code Online (Sandbox Code Playgroud)
3) 然后 FormState 将 FormFieldState 保存在一个列表中
void _register(FormFieldState<dynamic> field) {
_fields.add(field);
}
Run Code Online (Sandbox Code Playgroud)
4) 然后当 FormState 保存/验证时,它会循环遍历 FormFieldStates 列表
/// Saves every [FormField] that is a descendant of this [Form].
void save() {
for (FormFieldState<dynamic> field in _fields)
field.save();
}
Run Code Online (Sandbox Code Playgroud)
通过覆盖 build 方法,您会导致 FormField 未向 Form 注册,这就是为什么保存和加载 Form 不会调用自定义 FormField 的方法。
如果 FormState._register() 方法是公共的而不是私有的,你可以在你的 _LocationFormFieldState.build 方法中调用这个方法来将你的应用程序注册到表单,但遗憾的是,因为它是一个私有函数,你不能。
另请注意,如果您要在 CustomFormFieldState 的构建方法中调用 super.build() 函数,则会导致 StackOverflow
@override
Widget build(BuildContext context) {
super.build(context); //leads to StackOverflow!
return _buildFormField(); //anything you want
}
Run Code Online (Sandbox Code Playgroud)
Unk*_*kot -1
有同样的问题。对我来说,当我更换时它起作用了
return state.build(state.context);
Run Code Online (Sandbox Code Playgroud)
使用构建方法中的实际代码并从状态中删除构建方法覆盖。
| 归档时间: |
|
| 查看次数: |
13012 次 |
| 最近记录: |