You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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>格式即可,具体步骤如下:

  1. 先定义统一的高亮文本样式:
final TextStyle highlightTextStyle = TextStyle(
  color: Colors.blueAccent,
  fontWeight: FontWeight.w600,
);
  1. 假设从API获取到的单词列表为List<String> apiHighlightWords = ["Flutter", "Words"];,使用Map.fromIterable快速转换:
Map<String, HighlightedWord> highlightWordsMap = Map.fromIterable(
  apiHighlightWords,
  key: (word) => word,
  value: (word) => HighlightedWord(textStyle: highlightTextStyle),
);
  1. 将转换后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:10:27