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

Flutter State类访问组件属性报Undefined names错误

报错原因
  • controller、hintText是CustomTextField(Widget类)的成员属性,不属于其对应的State类_CustomTextFieldState。Flutter的StatefulWidget机制里,State子类访问关联Widget实例的属性,必须通过内置的widget对象引用,直接写属性名时,当前State作用域内没有对应变量声明,就会抛出未定义名称的错误。
  • 原代码里InputDecoration前加了const修饰,但hintText是运行时传入的动态参数,和编译时常量的声明规则冲突,也会触发编译错误,需要同步移除该const关键字。
修复步骤
  • 将TextFormField的controller参数从controller: controller修改为controller: widget.controller
  • 将InputDecoration的hintText参数从hintText: hintText修改为hintText: widget.hintText
  • 移除InputDecoration前面的const修饰符,固定不变的边框样式可以单独保留const修饰,不影响性能。
修复后的完整代码
import 'package:flutter/material.dart';

class CustomTextField extends StatefulWidget {
  final TextEditingController controller;
  final String hintText;

  const CustomTextField({
    super.key,
    required this.controller,
    required this.hintText,
  });

  @override
  State<CustomTextField> createState() => _CustomTextFieldState();
}

class _CustomTextFieldState extends State<CustomTextField> {
  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: widget.controller,
      decoration: InputDecoration(
        hintText: widget.hintText,
        border: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.black26,
          ),
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.black26,
          ),
        ),
      ),
      validator: (val) {
        // 在此处补充表单校验逻辑即可
        return null;
      },
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:06:34