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

如何移除API返回数据中的HTML标签?附Flutter请求代码

移除API数据中的HTML标签方案

下面给你两种可行的实现方式,适配你当前的Flutter代码:

方法一:使用正则表达式快速处理

适合结构简单的HTML内容,直接通过正则匹配并移除所有标签:

先定义一个移除HTML标签的工具函数:

String removeHtmlTags(String htmlText) {
  RegExp exp = RegExp(r'<[^>]*>', multiLine: true, caseSensitive: true);
  return htmlText.replaceAll(exp, '');
}

然后在你的fetchNews方法中,处理数据时调用这个函数:

fetchNews() async {
    setWordsState(WordsState.LOADING);
  
    final response = await http.post(Uri.parse(ApiUtil.WordFetch));
    data = json.decode(response.body);
    WordList wordslist = new WordList.fromJson(data["word"]);
    // 处理每个word中的HTML内容,假设你的Word模型有content字段需要清理
    allwords = wordslist.words.map((word) {
      return word.copyWith(
        content: removeHtmlTags(word.content)
      );
    }).toList();

    setWordsState(WordsState.LOADED);
}

方法二:使用html包(更可靠)

如果HTML内容结构复杂(比如嵌套标签、特殊实体),推荐使用官方维护的html包来解析:

  1. 先在pubspec.yaml中添加依赖:
dependencies:
  html: ^0.15.4 # 请使用最新版本
  1. 导入包并编写解析函数:
import 'package:html/parser.dart';

String parseHtmlToString(String htmlText) {
  return parse(htmlText).body?.text ?? '';
}
  1. 同样在fetchNews中替换处理逻辑:
fetchNews() async {
    setWordsState(WordsState.LOADING);
  
    final response = await http.post(Uri.parse(ApiUtil.WordFetch));
    data = json.decode(response.body);
    WordList wordslist = new WordList.fromJson(data["word"]);
    allwords = wordslist.words.map((word) {
      return word.copyWith(
        content: parseHtmlToString(word.content)
      );
    }).toList();

    setWordsState(WordsState.LOADED);
}

注意:请根据你的Word模型实际字段调整代码中的content字段名,确保对应到包含HTML标签的那个属性。

内容的提问来源于stack exchange,提问作者luke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:25:27