Flutter中如何对API返回文本的指定部分设置加粗格式
Flutter 局部文本加粗解决方案
要实现仅对文本中特定关键词("Lorem Ipsum"和"1500s")加粗,普通Text组件无法满足需求(仅支持统一样式),需使用Text.rich结合TextSpan实现,以下是两种可行方案:
方案一:手动构建TextSpan(适合文本结构固定的场景)
直接拆分文本为多个TextSpan,给目标关键词单独设置加粗样式:
return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text.rich( TextSpan( style: body1(), // 默认文本样式 children: [ TextSpan(text: "Lorem Ipsum", style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: " has been the industry's standard dummy text ever since the "), TextSpan(text: "1500s", style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: "."), ], ), ), ], );
方案二:自动生成格式化文本(灵活适配动态文本)
如果API返回的文本内容不固定,可编写工具函数自动识别关键词并生成带样式的TextSpan列表:
1. 编写格式化工具函数
List<TextSpan> getFormattedTextSpans( String text, List<String> keywords, TextStyle defaultStyle, TextStyle boldStyle, ) { List<TextSpan> spans = []; int currentIndex = 0; for (String keyword in keywords) { int keywordIndex = text.indexOf(keyword, currentIndex); if (keywordIndex == -1) { // 未找到当前关键词,直接添加剩余文本 spans.add(TextSpan(text: text.substring(currentIndex), style: defaultStyle)); currentIndex = text.length; break; } // 添加关键词之前的普通文本 if (keywordIndex > currentIndex) { spans.add(TextSpan(text: text.substring(currentIndex, keywordIndex), style: defaultStyle)); } // 添加加粗的关键词 spans.add(TextSpan(text: keyword, style: boldStyle)); currentIndex = keywordIndex + keyword.length; } // 添加剩余的普通文本 if (currentIndex < text.length) { spans.add(TextSpan(text: text.substring(currentIndex), style: defaultStyle)); } return spans; }
2. 在组件中使用工具函数
return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text.rich( TextSpan( style: body1(), children: getFormattedTextSpans( state.listExplanation[index].description!, ["Lorem Ipsum", "1500s"], body1(), body1().copyWith(fontWeight: FontWeight.bold), // 基于默认样式修改加粗 ), ), ), ], );
注意事项
- 关键词匹配默认大小写敏感,若需忽略大小写,可修改工具函数中的
indexOf逻辑(比如将文本和关键词都转为小写后比较) - 工具函数支持重复关键词、缺失关键词的场景,不会影响整体文本展示
- 加粗样式基于默认样式
body1()修改,确保字体、字号等与普通文本一致,仅添加加粗效果
内容的提问来源于stack exchange,提问作者Bilbo Baggins
相关产品推荐
相关产品推荐

