【问题标题】:How to avoid duplicated headlines from news api?如何避免新闻 api 中的重复标题?
【发布时间】:2021-03-09 12:41:18
【问题描述】:

我正在使用一个新闻 api,我经常在其中获得许多重复的标题。如何调整我的代码以避免这种情况?

final response = await http.get(url);

    final jsonData = jsonDecode(response.body);

    if (jsonData[Strings.status] == Strings.ok) {
      jsonData[Strings.articles].forEach((element) {
        if (element[Strings.urlToImg] != null &&
            element[SharedStrings.description] != null) {
          ArticleModel articleModel = ArticleModel(
            title: element[SharedStrings.title],
            author: element[Strings.author],
            description: element[SharedStrings.description],
            url: element[Strings.urlText],
            urlToImage: element[Strings.urlToImg],
            content: element[Strings.content], //context
          );
          news.add(articleModel);
getNews() async {
    News newsClass = News();
    await newsClass.getNews();
    articles = newsClass.news;
    setState(() => _loading = false);
  }

【问题讨论】:

    标签: api flutter


    【解决方案1】:

    行前

    news.add(articleModel);
    

    添加这个:

    var isDuplicated = false;
    for (var new in news) {
       if (new.title == articleModel.title) {
          isDuplicated = true;
       }
    }
    
    if (!isDuplicated) {
       // Now you can add it
       news.add(articleModel);
    }
    
    

    【讨论】:

    • 非常感谢。我刚刚将 new 更改为 article 并且它起作用了:)
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多