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

Flutter开发报错:参数类型Function无法赋值给void Function(String?)?如何解决?

报错核心原因

你定义的onSave、validator属性为无约束的泛型Function类型,和TextFormField对应参数要求的函数签名不匹配:

  • onSaved参数要求的类型是 void Function(String?)?:接收一个可空字符串参数、无返回值的可空函数
  • validator参数要求的类型是 String? Function(String?)?:接收一个可空字符串参数、返回可空字符串的可空函数

解决方案

把两个属性的类型从泛型Function改为匹配的具体函数类型即可,修改后的完整代码如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'custom_text.dart';

class CustomTextFormField extends StatelessWidget {
  final String text;
  final String hint;
  // 替换为和TextFormField参数匹配的具体函数类型签名
  final void Function(String?) onSave;
  final String? Function(String?) validator;

  const CustomTextFormField({
    super.key,
    required this.text,
    required this.hint,
    required this.onSave,
    required this.validator,
  });

  @override
  Widget build(BuildContext context) {
    var textFormField = TextFormField(
      onSaved: onSave,
      validator: validator,
      decoration: const InputDecoration(
          hintText: hint,
          hintStyle: TextStyle(
            color: Colors.black,
          ),
          fillColor: Colors.white),
    );
    return Container(
      child: Column(
        children: [
          CustomText(
            text: text,
            fontSize: 14,
            color: Colors.grey.shade900,
          ),
          textFormField, // 原代码漏了把输入框加入布局,这里补上
        ],
      ),
    );
  }
}

可选优化

如果你允许onSave和validator可选不传,可以在类型后加?,同时去掉构造函数的required修饰,TextFormField会自动处理空值;也可以用typedef提前定义类型简化重复代码:

// 提前定义函数类型别名
typedef OnSaveCallback = void Function(String?);
typedef ValidatorCallback = String? Function(String?);

// 定义属性时直接用别名即可
final OnSaveCallback onSave;
final ValidatorCallback validator;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:45:03