Flutter自定义FormField:不调用validate和save方法

问题描述 投票:0回答:2

我对Flutter很新,我正在努力创建一个自定义表单字段。问题是我的自定义FormField中的验证器和onSaved方法都没有被调用。当我触发formKey.currentState.validate()formKey.currentState.save()时,我真的无法理解为什么他们会被忽略。

现在这是一个非常简单的小部件,带有输入文本和按钮。该按钮将获取用户的当前位置,并使用当前地址更新文本字段。当用户在文本字段中输入地址时,它将在焦点丢失时获取该地址的位置(我还与Google地图集成,但我将其简化以隔离问题)。

这是我的表单字段的构造函数:

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();
      }
}

因为我需要在自定义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}');
    }
  }

这是我在我的应用程序中实例化它的方式。这里没什么特别的;我把它放在带有表格密钥的表格中。还有另一个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(),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      }

由表单提交按钮触发的提交方法将尝试验证然后保存表单。

只需打印保存在表单中的数据:

void _submitForm() {
    print('formdata : $_formData');

    if (!_formKey.currentState.validate()) {
      return;
    }
    _formKey.currentState.save();

    print('formdata : $_formData');
}

但是_formData['location']总是返回null,并且永远不会调用验证器(在日志中没有打印'验证器位置'或'保存位置')。

我创建了一个样本仓库来重现这个问题。您可以尝试运行该项目,首先单击“找到我”!按钮,然后在https://github.com/manumura/flutter-location-form-field保存按钮

flutter
2个回答
0
投票

有同样的问题。对我而言,当我更换时它起作用了

return state.build(state.context);

使用构建方法中的实际代码并从状态中删除构建方法覆盖。


1
投票

答案1:为Builder构建构建方法

替换FormField的构建器

builder: (FormFieldState<LocationData> state) {
              return state.build(state.context);
            });

使用自定义构建器功能

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,
        ),
      ],
    });

答案2:Pseudo CustomFormFieldState

您无法扩展FormFieldState,因为覆盖“build”函数会导致错误(如下所述)

但是你可以创建一个Widget,它将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
  }
}

说明

扩展FormFieldState不起作用的原因是因为覆盖FormFieldState对象中的构建方法会导致FormFieldState不向Form本身注册。

下面是我为了解释而遵循的功能列表

1)您的_LocationFormFieldState会覆盖构建方法,这意味着FormFieldState的构建方法永远不会执行

@override
 Widget build(BuildContext context)

2)FormFieldState将自身注册到当前FormState的构建方法

///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);
    }

3)然后FormState将FormFieldState保存在List中

  void _register(FormFieldState<dynamic> field) {
    _fields.add(field);
  }

4)然后当FormState保存/验证时,它循环遍历FormFieldStates列表

/// Saves every [FormField] that is a descendant of this [Form].
  void save() {
    for (FormFieldState<dynamic> field in _fields)
      field.save();
  }

通过重写构建方法,您将导致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
  }
© www.soinside.com 2019 - 2024. All rights reserved.