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

Flutter中TextFormField的validator参数报类型不匹配是什么原因

报错原因

报错本质是函数类型不匹配:

  • Flutter原生TextFormField的validator参数要求的类型是String? Function(String?)?:该函数接收可选字符串类型的输入值,返回值为可选字符串类型——输入验证通过时返回null,验证不通过时返回描述错误的提示字符串。
  • 你自定义的CustomTextFormField里,validator属性的类型被声明为void Function(String?)?,无返回值,不符合原生参数的类型要求,因此赋值时报错。

修复方案

仅需要修改自定义组件中validator属性的类型声明,和原生要求的类型对齐即可,修改后的完整代码如下:

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

class CustomTextFormField extends StatelessWidget {
  final String hintText;
  final Color color;
  final Color fillColor;
  final void Function(String?)? onSave;
  // 将validator的返回值类型从void改为String?即可
  final String? Function(String?)? validator;

  const CustomTextFormField({
     this.hintText = "",
     this.color = Colors.black,
     this.fillColor = Colors.grey,
     this.onSave ,
     this.validator,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TextFormField(
        onSaved: onSave,
        validator: validator,
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            color: color,
          ),
          fillColor: fillColor,
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:39:05