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

Flutter自定义TextField报错:无法将Null赋值给const构造器的TextEditingController参数

Flutter自定义TextField传递TextEditingController报错解决

问题描述

我是Flutter开发新手,创建了一个可接收样式参数和TextEditingController的自定义TextField组件,但传递controller时出现如下错误:

A value of type 'Null' can't be assigned to a parameter of type 'TextEditingController' in a const constructor.
Try using a subtype, or removing the keyword 'const'.

我的代码

自定义组件代码

// Custom Widget
class TestEditText extends StatelessWidget {
  final Color fontColor;
  final String hintText;
  final Color hintColor;
  final bool isBorder;
  final double borderWidth;
  final Color borderColor;
  final bool isIcon;
  final Icon prefixIcon;
  final TextEditingController textController;

  const TestEditText({
    Key? key,
    required this.textController,
    required this.fontColor,
    required this.hintText,
    required this.hintColor,
    this.isBorder = true,
    this.borderWidth = 0.5,
    this.borderColor = const Color.fromRGBO(204, 204, 204, 1),
    this.isIcon = true,
    this.prefixIcon = const Icon(Icons.abc),
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return PhysicalModel(
        color: Colors.white,
        elevation: 5.0,
        shadowColor: Colors.black54,
        child: TextField(
          controller: textController,
          style: TextStyle(color: fontColor),
          decoration: InputDecoration(
              hintText: hintText,
              hintStyle: TextStyle(color: hintColor),
              focusedBorder: OutlineInputBorder(
                  borderSide:
                      BorderSide(width: borderWidth, color: borderColor),
                  borderRadius: const BorderRadius.all(Radius.circular(0))),
              enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(width: borderWidth, color: borderColor),
              ),
              prefixIcon: prefixIcon),
        ));
  }
}

使用自定义组件的代码

// Use of Custom Widget
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController txtEmailController = TextEditingController();
  TextEditingController txtPasswordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: Container(
          alignment: Alignment.topLeft,
          margin: const EdgeInsets.fromLTRB(10, 50, 0, 10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [              
              Container(
                height: 50,
                margin: const EdgeInsets.only(left: 5, right: 15),
                child: const Center(
                    child: TestEditText(
                  textController: txtEmailController,
                  hintText: 'Enter Email',
                  hintColor: Color.fromRGBO(119, 119, 119, 1),
                  fontColor: Color.fromRGBO(119, 119, 119, 1),
                  isBorder: true,
                  borderWidth: 0.5,
                  borderColor: Color.fromRGBO(204, 204, 204, 1),
                  isIcon: true,
                  prefixIcon: Icon(
                    Icons.email_outlined,
                  ),
                )),
              ),
              const SizedBox(
                height: 20,
              ),
              Container(
                height: 50,
                margin: const EdgeInsets.only(left: 5, right: 15),
                child: const Center(
                    child: TestEditText(
                  textController: txtPasswordController,
                  hintText: 'Enter Password',
                  hintColor: Color.fromRGBO(119, 119, 119, 1),
                  fontColor: Color.fromRGBO(119, 119, 119, 1),
                  isBorder: true,
                  borderWidth: 0.5,
                  borderColor: Color.fromRGBO(204, 204, 204, 1),
                  isIcon: true,
                  prefixIcon: Icon(
                    Icons.lock_outlined,
                  ),
                )),
              ),
              const SizedBox(
                height: 25,
              ),
              GestureDetector(
                onTap: () async {},
                child: Container(
                  margin: const EdgeInsets.only(right: 10),
                  child: ElevatedButton(
                    style: const ButtonStyle(
                      backgroundColor: MaterialStatePropertyAll(
                          Color.fromRGBO(2, 118, 236, 1)),
                      foregroundColor: MaterialStatePropertyAll(Colors.white),
                    ),
                    onPressed: null,
                    child: Container(
                      height: 50,
                      width: MediaQuery.of(context).size.width * 0.7,
                      alignment: Alignment.center,
                      child:
                          const Text("Login", style: TextStyle(fontSize: 18)),
                    ),
                  ),
                ),
              ),              
            ],
          ),
        ));
  }
}

解决方案

核心问题原因

报错根源在于调用TestEditText时加了const关键字,但TextEditingController是运行时初始化的状态类实例,属于非编译时常量对象,无法用于const构造函数中。

修复步骤

  1. 移除使用处的const修饰符:在LoginPage中调用TestEditText时,去掉const,同时外层的const Center也要移除(因为子组件不再是const):

    // 修改前
    child: const Center(
        child: TestEditText(
      textController: txtEmailController,
      ...
    ))
    
    // 修改后
    child: Center(
        child: TestEditText(
      textController: txtEmailController,
      ...
    ))
    

    两个TestEditText实例都需要做此修改。

  2. 可选:调整自定义组件的构造函数:如果你的自定义组件不需要作为const使用,可以直接去掉TestEditText构造函数的const关键字,避免后续误用:

    // 修改前
    const TestEditText({...}) : super(key: key);
    
    // 修改后
    TestEditText({...}) : super(key: key);
    

修复后的LoginPage关键代码片段

Container(
  height: 50,
  margin: const EdgeInsets.only(left: 5, right: 15),
  child: Center(
      child: TestEditText(
    textController: txtEmailController,
    hintText: 'Enter Email',
    hintColor: const Color.fromRGBO(119, 119, 119, 1),
    fontColor: const Color.fromRGBO(119, 119, 119, 1),
    isBorder: true,
    borderWidth: 0.5,
    borderColor: const Color.fromRGBO(204, 204, 204, 1),
    isIcon: true,
    prefixIcon: const Icon(
      Icons.email_outlined,
    ),
  )),
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:10:02