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
相关产品推荐
相关产品推荐

