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

Flutter调用NewsAPI:如何从JSON数据中获取新闻源ID

解决方案

1. 调整SourceModel适配两种数据源

原SourceModel的字段均为必填项,但新闻列表返回的source仅包含id和name,需将非必要字段改为可选:

class SourceModel {
  String id;
  String name;
  String? description;
  String? url;
  String? category;
  String? country;
  String? language;

  SourceModel({
    required this.id,
    required this.name,
    this.description,
    this.url,
    this.category,
    this.country,
    this.language,
  });
}

2. 更新ArticleModel添加新闻源属性

在ArticleModel中新增SourceModel类型的属性,用于存储单条新闻对应的源信息:

class ArticleModel {
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? content;
  String? publishedAt;
  SourceModel? source; // 新增新闻源属性

  ArticleModel({
    required this.author,
    required this.title,
    required this.description,
    required this.url,
    required this.urlToImage,
    required this.content,
    required this.publishedAt,
    this.source, // 构造函数添加对应参数
  });
}

3. 修改getNews方法解析新闻源数据

在getNews方法中解析source节点数据,同时修正原代码中content字段的拼写错误(element['context']改为element['content']):

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async {
    String url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=45dd80f272ae40d5af76a796acee8529";

    var response = await http.get(Uri.parse(url));
    var jsonData = jsonDecode(response.body);

    if (jsonData['status'] == 'ok') {
      jsonData['articles'].forEach((element) {
        if (element['urlToImage'] != null && element['description'] != null) {
          // 解析新闻源节点
          var sourceJson = element['source'];
          SourceModel? articleSource;
          if (sourceJson != null && sourceJson['id'] != null && sourceJson['name'] != null) {
            articleSource = SourceModel(
              id: sourceJson['id'],
              name: sourceJson['name'],
            );
          }

          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['content'], // 修正拼写错误
            publishedAt: element['publishedAt'],
            source: articleSource, // 传入新闻源实例
          );
          news.add(articleModel);
        }
      });
    }
  }
}

4. 获取并使用新闻源ID

后续可通过articleModel.source?.id直接访问单条新闻对应的源ID。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:05:19