如何在Flutter的TextFormField中修改输入内容里话题标签(#)的文本颜色
要实现TextFormField输入时#话题标签单独变色,核心逻辑是重写文本输入控制器的buildTextSpan方法,对匹配到的话题片段单独设置样式,无需修改原有TextFormField的其他配置,具体实现步骤如下:
步骤1:自定义带高亮逻辑的文本控制器
继承TextEditingController,重写富文本构建逻辑,用正则匹配所有话题标签,对匹配到的内容单独应用高亮样式:
class HighlightCaptionController extends TextEditingController { /// 话题标签的高亮样式 final TextStyle hashtagStyle; /// 普通文本的样式 final TextStyle normalTextStyle; HighlightCaptionController({ required this.hashtagStyle, required this.normalTextStyle, String? initText, }) : super(text: initText); @override TextSpan buildTextSpan({ required BuildContext context, TextStyle? baseStyle, required bool withComposing }) { List<TextSpan> spanChildren = []; // 话题匹配正则,支持中文、字母、数字组合的话题,可根据需求自行调整 // 若要支持带特殊字符的话题,可改为 RegExp(r'#\S+') 匹配#后所有非空白字符 final hashtagRegex = RegExp(r'#[\u4e00-\u9fa5\w]+'); text.splitMapJoin( hashtagRegex, onMatch: (Match match) { spanChildren.add(TextSpan( text: match.group(0), style: hashtagStyle, )); return ''; }, onNonMatch: (String normalText) { spanChildren.add(TextSpan( text: normalText, style: normalTextStyle, )); return ''; }, ); return TextSpan(style: baseStyle, children: spanChildren); } }
步骤2:替换原有输入控制器
将你原来PostController中的captionController替换为上面自定义的控制器,初始化时传入对应样式:
// 放在你的PostController内初始化即可 final captionController = HighlightCaptionController( normalTextStyle: const TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold, ), hashtagStyle: const TextStyle( // 自定义话题标签的颜色,可自行调整 color: Colors.blueAccent, fontSize: 18, fontWeight: FontWeight.bold, ), );
步骤3:调整原有TextFormField配置
删除原有TextFormField中的style属性(样式已在控制器中定义),最终代码如下:
TextFormField( minLines: 1, maxLines: 5, keyboardType: TextInputType.multiline, controller: postController.captionController, decoration: const InputDecoration.collapsed( hintText: 'caption', hintStyle: TextStyle( fontSize: 15, ), ), validator: (value) { return postController.validateCaption(value!); }, ),
内容的提问来源于stack exchange,提问作者stock
相关产品推荐
相关产品推荐

