flutter 返回类型“String”不是闭包上下文所要求的“String”

pvabu6sv  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(181)

我正在尝试创建一个TextFormField模板。该函数从UI中获取多个参数,下面是该函数:

TextFormField _buildRoundedTextField(
    String label,
    TextEditingController controller, {
    TextInputType? keyboardType,
    bool isPassword = false,
    String Function(String)? validationState, 
  }) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      obscureText: isPassword,
      decoration: InputDecoration(
        labelText: label,
        filled: true,
        fillColor: Colors.grey[200],
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
      ),
      validator: validatorState
        return null;
      },
    );
  }

字符串
问题出现在我通过函数传递验证器时,如下所示:

_buildRoundedTextField('Family Name', familyNameController,
                validationState: (value) {
              String pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
              RegExp regExp = RegExp(pattern);
              if (!regExp.hasMatch(value)) {
                return 'Enter a valid email';
              }
              return null;
            }),


它不会返回null,我不确定返回什么字符串。

soat7uwm

soat7uwm1#

试试这个代码,我做了一些修改。

  • validationState类型更改为FormFieldValidator<String>?
  • 添加新变量AutovalidateMode

小部件:

TextFormField _buildRoundedTextField(
    String label,
    TextEditingController controller, {
    TextInputType? keyboardType,
    bool isPassword = false,
    AutovalidateMode validationMode = AutovalidateMode.disabled,
    FormFieldValidator<String>? validationState,
  }) {
    return TextFormField(
        controller: controller,
        keyboardType: keyboardType,
        obscureText: isPassword,
        decoration: InputDecoration(
          labelText: label,
          filled: true,
          fillColor: Colors.grey[200],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
        autovalidateMode: validationMode,
        validator: validationState);
  }

字符串
Widget实现:

Center(
    child: _buildRoundedTextField('Family Name', familyNameController,
        validationMode: AutovalidateMode.onUserInteraction,
        validationState: (value) {
      String pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
      RegExp regExp = RegExp(pattern);
      if (value != null && !regExp.hasMatch(value)) {
        return 'Enter a valid email';
      }
      return null;
    }),
  ),


结果:


的数据


相关问题