Flutter中能否为TextFormField的用户输入文本设置多色显示?
在Flutter的TextFormField中实现输入文本多色显示
可以实现同一输入框内用户输入文本的多色显示,核心思路是通过自定义TextEditingController,重写其buildTextSpan方法,根据设定的规则为不同文本片段应用不同样式。
实现步骤
自定义
TextEditingController,添加样式匹配规则
下面的示例会将输入中#开头的文本设为红色,@开头的文本设为蓝色:class ColoredTextController extends TextEditingController { final Map<Pattern, TextStyle> styleRules; ColoredTextController({required this.styleRules, String? text}) : super(text: text); @override TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) { final defaultStyle = style ?? const TextStyle(); final List<TextSpan> spans = []; String remainingText = text; // 遍历样式规则,拆分文本并应用对应样式 styleRules.forEach((pattern, textStyle) { final matches = pattern.allMatches(remainingText); if (matches.isNotEmpty) { for (final match in matches) { final start = match.start; final end = match.end; // 添加匹配前的普通文本 if (start > 0) { spans.add(TextSpan(text: remainingText.substring(0, start), style: defaultStyle)); } // 添加匹配到的带样式文本 spans.add(TextSpan(text: remainingText.substring(start, end), style: defaultStyle.merge(textStyle))); // 更新剩余文本 remainingText = remainingText.substring(end); } } }); // 添加最后剩余的普通文本 if (remainingText.isNotEmpty) { spans.add(TextSpan(text: remainingText, style: defaultStyle)); } return TextSpan(style: defaultStyle, children: spans); } }在
TextFormField中使用自定义controllerTextFormField( controller: ColoredTextController( styleRules: { RegExp(r'#\w+'): const TextStyle(color: Colors.red, fontWeight: FontWeight.bold), RegExp(r'@\w+'): const TextStyle(color: Colors.blue, fontStyle: FontStyle.italic), }, ), decoration: const InputDecoration( labelText: '输入带#或@的文本', border: OutlineInputBorder(), ), maxLines: null, // 可选:支持多行输入 )
说明
- 你可以根据需求修改
styleRules中的匹配规则(比如正则表达式、固定字符串)和对应的样式,实现更复杂的多色效果 - 这种方式完全保留
TextFormField的表单验证、输入监听等原生功能,同时实现了输入文本的多色渲染 - 如果需要实时动态调整样式规则,只需更新controller的
styleRules并调用notifyListeners()即可
内容的提问来源于stack exchange,提问作者Graham Wheeler
相关产品推荐
相关产品推荐

