You need to enable JavaScript to run this app. Flutter StatelessWidget转StatefulWidget实现密码显隐报错解决
优惠活动
大模型
产品
解决方案
定价
更多

Flutter StatelessWidget转StatefulWidget实现密码显隐报错解决

Flutter 密码显隐功能实现报错解决方案

问题背景

要实现密码输入框点击图标切换显隐的效果,该功能需要维护布尔状态、调用setState方法更新视图,StatelessWidget无法满足需求,因此参照教程将组件改造为StatefulWidget,改造完成后代码出现编译报错。

报错信息(已翻译)

36行32列:错误:类_RoundedPasswordFieldState中未定义 setter _isSecret

  • _RoundedPasswordFieldState 来自 package:yona/Login/Components/rounded_password_field.dart(本地路径为 lib/Login/Components/rounded_password_field.dart)
    请将名称修正为已存在的 setter 名称,或者定义名为 _isSecret 的字段或 setter 方法。

报错原因

没有在State子类中提前定义控制密码显隐状态的私有布尔变量_isSecret,赋值时编译器无法找到对应的字段抛出错误。

正确实现代码

class _RoundedPasswordFieldState extends State<RoundedPasswordField> {
  // 控制密码显隐的状态变量,默认值为true代表隐藏密码
  bool _isSecret = true;

  @override
  Widget build(BuildContext context) {
    return TextFieldContainer(
      child: TextFormField(
        obscureText: _isSecret,
        decoration: InputDecoration(
          hintText: "Password",
          border: InputBorder.none,
          icon: Icon(
            Icons.lock,
            color: DarkTurquoise,
          ),
          suffixIcon: InkWell(
            onTap: () =>
                setState(() => _isSecret = !_isSecret),
            child: Icon(!_isSecret
                ? Icons.visibility
                : Icons.visibility_off, color: DarkTurquoise),
          ),
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:15:00