Flutter中TextField密码显示/隐藏实现及obscureText报错解决
问题排查与解决方案
错误原因
密码输入框的TextField被标记为const,但obscureText: oT引用了组件状态中的非const变量oT。const组件只能使用编译时常量,两者冲突导致报错。
完整修正代码
import 'package:flutter/material.dart'; class SignUpPage extends StatefulWidget { const SignUpPage({super.key}); @override State<SignUpPage> createState() => _SignUpPageState(); } class _SignUpPageState extends State<SignUpPage> { bool _obscurePassword = true; // 优化变量命名,提升可读性 @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, decoration: const BoxDecoration(color: Colors.white), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Welcome Back", style: TextStyle( color: Colors.black, fontStyle: FontStyle.normal, fontFamily: "nunito", fontWeight: FontWeight.bold, fontSize: 30, ), ), const Text( "House Hunting, Simplified", style: TextStyle( fontSize: 15, fontFamily: "nunito", fontWeight: FontWeight.w200, fontStyle: FontStyle.normal, color: Colors.black, ), ), const Padding(padding: EdgeInsets.only(top: 20)), Container( height: 50, width: 320, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(15)), color: Colors.white, border: Border( top: BorderSide(color: Colors.black), right: BorderSide(color: Colors.black), bottom: BorderSide(color: Colors.black), left: BorderSide(color: Colors.black), ), ), child: const TextField( decoration: InputDecoration( prefixIcon: Icon(Icons.person_outline_rounded, color: Colors.black), hintText: "Enter Your UserName", border: InputBorder.none, ), ), ), Container( height: 50, width: 320, margin: const EdgeInsets.only(top: 10), decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(15)), color: Colors.white, border: Border( top: BorderSide(color: Colors.black), right: BorderSide(color: Colors.black), bottom: BorderSide(color: Colors.black), left: BorderSide(color: Colors.black), ), ), // 移除const修饰符,允许组件引用状态变量 child: TextField( decoration: InputDecoration( prefixIcon: Icon(Icons.password_rounded, color: Colors.black), suffixIcon: IconButton( padding: EdgeInsets.zero, icon: Icon( // 根据状态切换显示图标 _obscurePassword ? Icons.remove_red_eye_outlined : Icons.visibility_off_outlined, color: Colors.black, ), onPressed: () { // 点击切换密码可见性,更新组件状态 setState(() { _obscurePassword = !_obscurePassword; }); }, ), hintText: "Enter Your Password", border: InputBorder.none, ), obscureText: _obscurePassword, ), ), ], ), ), ), ); } }
关键修改点
- 移除密码
TextField的const修饰符,解决变量引用冲突 - 将原变量
oT重命名为_obscurePassword,让代码语义更清晰 - 将
suffixIcon的普通Icon替换为IconButton,添加点击交互逻辑 - 通过
setState更新状态变量,实现密码显示/隐藏的动态切换 - 根据状态值切换图标样式,给用户直观的交互反馈
内容的提问来源于stack exchange,提问作者Dhrumil Rupapara
相关产品推荐
相关产品推荐

