Flutter存在多个TextField时如何在聚焦时修改标签文字颜色
实现方法
Flutter 的 InputDecoration 原生提供了 floatingLabelStyle 属性,专门用于配置 TextField 获得焦点、标签上浮时的样式,你不需要额外编写焦点监听逻辑,只需要给两个 TextField 的 InputDecoration 新增该属性即可,配置的颜色和你当前光标、聚焦边框的颜色保持一致就行。
修改后完整代码
// 用户名输入框 Padding( padding: const EdgeInsets.only(left: 32.0, right: 32.0), child: TextField( cursorColor: Color(0xFFD9A506), decoration: InputDecoration( labelText: 'Username', focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Color(0xFFD9A506), style: BorderStyle.solid ) ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Color(0xFF919191)), ), labelStyle: TextStyle(color: Color(0xFF919191)), // 新增这一行,配置聚焦时的标签颜色 floatingLabelStyle: TextStyle(color: Color(0xFFD9A506)), ), onChanged: (value) { userName = value; setState(() { isTextFiledFocus = userName.isNotEmpty && password.isNotEmpty; }); }, ), ), // 密码输入框 Padding( padding: const EdgeInsets.only(top: 38.0, left: 32.0, right: 32.0), child: TextField( cursorColor: Color(0xFFD9A506), obscureText: isHidePassword, enableSuggestions: false, autocorrect: false, decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Color(0xFFD9A506), style: BorderStyle.solid ) ), labelText: 'Password', suffixIcon: IconButton( color: Color(0xFF919191), onPressed: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } setState(() { isHidePassword = !isHidePassword; }); }, icon: Icon(isHidePassword ? Icons.visibility : Icons.visibility_off ) ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Color(0xFF919191)), ), labelStyle: TextStyle(color: Color(0xFF919191)), // 同样新增这一行配置 floatingLabelStyle: TextStyle(color: Color(0xFFD9A506)), ), onChanged: (value) { password = value; setState(() { isTextFiledFocus = userName.isNotEmpty && password.isNotEmpty; }); } ), )
补充说明
如果你后续有更复杂的焦点状态控制需求,也可以给每个 TextField 绑定独立的 FocusNode,监听 hasFocus 状态后动态修改 labelStyle,但当前场景用原生提供的 floatingLabelStyle 已经可以完全满足需求,代码更简洁也不会有额外的性能开销。
内容的提问来源于stack exchange,提问作者Hemavathi
相关产品推荐
相关产品推荐

