You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter参数类型不匹配错误:Function()?无法赋值给String? Function(String?)?

Dart参数类型不匹配错误修复

错误信息

参数类型'dynamic Function()?'无法分配给参数类型'String? Function(String?)?'
错误类型:argument_type_not_assignable
位置:[firsfapp] lib/shared/components/components.dart:42

相关代码

Widget defaultButton({
  double width = double.infinity,
  Color background = Colors.blue,
  @required void Function()? function,
  @required String? text,
  bool isUpperCase = true,
  double radius = 65.0,
}) => Container(
  width: width,
  height: 40.0,
  child: MaterialButton(
    onPressed: function,
    child: Text(
      isUpperCase ? text!.toUpperCase() : text!,
      style: TextStyle(
        color: Colors.white,
      ),
    ),
  ),
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(
      radius,
    ),
    color: background,
  ),
);

Widget dfailtFormField({
  @required TextEditingController? controller,
  @required TextInputType? type,
  Function(String)? onSubmit,
  Function(String)? onChange,
  Function()? validate,
}) => TextFormField(
  controller: controller,
  keyboardType: type,
  onFieldSubmitted: onSubmit,
  onChanged: onChange,
  validator: validate,
  decoration: InputDecoration(
    labelText: 'Email Address',
    border: OutlineInputBorder(),
    prefixIcon: Icon(
      Icons.email,
    ),
  ),
);

问题原因

dfailtFormField组件中validate参数的类型定义为Function()?,但TextFormField的validator属性要求的类型是String? Function(String?)?——该函数需要接收一个String?类型的输入参数(当前输入框的文本内容),返回值为String?(返回null表示验证通过,返回字符串则为错误提示文本),两者类型不匹配导致报错。

修复方案

将dfailtFormField的validate参数类型修正为String? Function(String?)?,确保和TextFormField的validator要求一致。

修改后的dfailtFormField代码:

Widget dfailtFormField({
  @required TextEditingController? controller,
  @required TextInputType? type,
  Function(String)? onSubmit,
  Function(String)? onChange,
  // 修正参数类型
  String? Function(String?)? validate,
}) => TextFormField(
  controller: controller,
  keyboardType: type,
  onFieldSubmitted: onSubmit,
  onChanged: onChange,
  validator: validate,
  decoration: InputDecoration(
    labelText: 'Email Address',
    border: OutlineInputBorder(),
    prefixIcon: Icon(
      Icons.email,
    ),
  ),
);

使用组件时,传入的验证函数需符合该签名,示例:

dfailtFormField(
  validate: (value) {
    if (value == null || value.isEmpty) {
      return '请输入邮箱地址';
    }
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegex.hasMatch(value)) {
      return '请输入有效的邮箱地址';
    }
    return null;
  },
  // 其他参数...
)

内容的提问来源于stack exchange,提问作者Hassani Chamseddine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:46:29