Flutter中如何为TextField与TextFormField的标签添加红色星号
Flutter表单必填项TextField/TextFormField添加红色星号实现方案

实现核心:Flutter的TextField和TextFormField的InputDecoration提供了label属性,支持传入自定义Widget,代替原来只能传字符串的labelText,就可以实现带红色星号的必填标签效果,而且完全保留原生标签的浮动、样式变化等交互特性。
基础实现代码
直接在组件的decoration中传入自定义RichText作为label即可:
import 'package:flutter/material.dart'; class RequiredFormDemo extends StatelessWidget { const RequiredFormDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // TextFormField 示例 TextFormField( decoration: InputDecoration( // 替换labelText为自定义label label: RichText( text: const TextSpan( text: '用户名', style: TextStyle(color: Colors.grey, fontSize: 16), children: [ TextSpan( text: ' *', style: TextStyle(color: Colors.red, fontSize: 16), ) ], ), ), border: const OutlineInputBorder(), ), ), const SizedBox(height: 20), // TextField 示例,用法完全一致 TextField( decoration: InputDecoration( label: RichText( text: const TextSpan( text: '邮箱', style: TextStyle(color: Colors.grey, fontSize: 16), children: [ TextSpan( text: ' *', style: TextStyle(color: Colors.red, fontSize: 16), ) ], ), ), border: const OutlineInputBorder(), ), ) ], ), ), ); } }
封装复用方案
如果项目中大量用到必填表单项,可以把必填标签封装为通用方法,减少重复代码:
// 通用生成必填标签的工具方法 Widget buildRequiredLabel( String labelText, { Color labelColor = Colors.grey, Color requiredColor = Colors.red, double fontSize = 16, }) { return RichText( text: TextSpan( text: labelText, style: TextStyle(color: labelColor, fontSize: fontSize), children: [ TextSpan( text: ' *', style: TextStyle(color: requiredColor, fontSize: fontSize), ) ], ), ); }
封装后调用仅需一行代码:
TextFormField( decoration: InputDecoration( label: buildRequiredLabel('手机号码'), border: const OutlineInputBorder(), ), )
注意事项
- 该方案兼容Flutter 2.0及以上版本,
label属性自带的浮动效果和原生labelText完全一致,输入内容时星号会和标签一起上浮缩小,无需额外处理交互逻辑。 - 若使用低于2.0的Flutter版本不支持
label属性,可以将标签单独放在TextField外部组合,或者升级SDK版本适配。
内容的提问来源于stack exchange,提问作者Root Root
相关产品推荐
相关产品推荐

