行业知识
Flutter自定义输入框同时出现多种字体颜色
2026-10-20 10:39:31
来源:互联网转载
Flutter自定义输入框同时出现多种字体颜色
- 效果展示
- 基本逻辑
- 代���示例
效果展示
输入框内效果
基本逻辑
主要通过重写TextEditingController中的buildTextSpan方法实现,通过在buildTextSpan中将内容手动切割(本人通过正则表达式将#这些话题分割开来),然后组装成为一个TextSpan 返回出去
buildTextSpan 是一个用于构建 TextSpan 对象的方法,它通常用于自定义文本样式或在 RichText 中构建富文本。
代码示例
class CustomTextEditingController extends TextEditingController { //正则表达式切割文本内容 List splitByHash(String input) { RegExp regex = RegExp(r'#([a-zA-Z0-9\u4e00-\u9fa5\?]+)'); Iterable matches = regex.allMatches(input); List result = []; int lastIndex = 0; for (Match match in matches) { String matchText = match.group(0)!; int matchIndex = match.start; // Add the text before the match if (matchIndex > lastIndex) { result.add(input.substring(lastIndex, matchIndex)); } // Add the matched text result.add(matchText); lastIndex = matchIndex + matchText.length; } // Add the remaining text after the last match if (lastIndex
- 代���示例
上一篇:mc服务器怎么进不去了?
下一篇:机房保密哪里不能拍?