如何在highlight_text 1.6.0中从API加载列表生成高亮词映射?
问题
我需要对文本中的部分单词进行高亮处理,使用了highlight_text 1.6.0包。以下是静态配置的代码示例:
Map<String, HighlightedWord> words = { "Flutter": HighlightedWord( textStyle: textStyle, ), "words": HighlightedWord( textStyle: textStyle, ), }; TextHighlight( text: text, words: words, matchCase: false, textStyle: TextStyle( fontSize: 14.0, color: Colors.black, ), textAlign: TextAlign.justify, )
静态配置的情况下功能正常。请问是否可以从API获取如下形式的单词列表,替代上述静态Map来实现高亮?
List=["Flutter", "Words"]
解决方案
完全可以实现,只需要将API返回的字符串列表转换成TextHighlight组件所需的Map<String, HighlightedWord>格式即可,具体步骤如下:
- 先定义统一的高亮文本样式:
final TextStyle highlightTextStyle = TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.w600, );
- 假设从API获取到的单词列表为
List<String> apiHighlightWords = ["Flutter", "Words"];,使用Map.fromIterable快速转换:
Map<String, HighlightedWord> highlightWordsMap = Map.fromIterable( apiHighlightWords, key: (word) => word, value: (word) => HighlightedWord(textStyle: highlightTextStyle), );
- 将转换后的Map传入
TextHighlight组件的words参数即可:
TextHighlight( text: text, words: highlightWordsMap, matchCase: false, textStyle: TextStyle( fontSize: 14.0, color: Colors.black, ), textAlign: TextAlign.justify, )
额外注意事项
- 若API返回的单词存在大小写差异,保持
matchCase: false即可忽略大小写进行匹配 - 由于API请求是异步操作,需使用
FutureBuilder等组件等待数据返回后再渲染TextHighlight,避免空数据异常
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

