简体   繁体   English

我在尝试使用 RSS 访问数据时遇到问题

[英]i am having issue while trying to access data using rss

Error message: Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List>'错误消息:未处理的异常:类型“_InternalLinkedHashMap<String, dynamic>”不是“FutureOr<List>”类型的子类型

import 'dart:convert';

import 'package:xml2json/xml2json.dart';
import 'package:http/http.dart' as http;

Future<List> rssToJson(String category,
    {String baseUrl="https://www.hindustantimes.com/feeds/rss/"}) async {
  var client = http.Client();
  final myTransformer = Xml2Json();
  return await client.get(baseUrl + category + '/rssfeed.xml').then((response) {
    return response.body;
  }).then((bodyString) {
    myTransformer.parse(bodyString);
    var json = myTransformer.toGData();
    return jsonDecode(json)['rss']['channel']['item'];
  });
}

This is where I am trying to use the data received from rss:这是我尝试使用从 rss 收到的数据的地方:

Map<String, List> newsData = Map<String, List>();
bool isLoading = true;
getData() async{
    Future.wait([
      rssToJson('topnews'),
      rssToJson('india'),
      rssToJson('world-news'),
      rssToJson('business'),
      rssToJson('sports'),
      rssToJson('cricket'),
      rssToJson('education'),
      rssToJson('entertainment'),
      rssToJson('lifestyle'),
      rssToJson('health'),
      rssToJson('books'),
      rssToJson('trending'),
    ]).then((value) {
      value[0] = [];
      value.forEach((element) {
        value[0].addAll([...element ?? []]);
      });
      value[0].shuffle();
      newsData['topnews'] = value[0].sublist(0, 10);
      newsData['india'] = value[1];
      newsData['world'] = value[2];
      newsData['business'] = value[3];
      newsData['sports'] = value[4];
      newsData['cricket'] = value[5];
      newsData['education'] = value[6];
      newsData['entertainment'] = value[7];
      newsData['lifestyle'] = value[8];
      newsData['health-fitness'] = value[9];
      newsData['books'] = value[10];
      newsData['its-viral'] = value[11];
      setState(() {
        isLoading = false;
      });
    });
  }

I tried Future<dynamic> rssToJson() as well but still not working...any help would be appreciated.我也尝试Future<dynamic> rssToJson()但仍然无法正常工作......任何帮助将不胜感激。 Thanks in advance.提前致谢。

NetService网络服务

import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;

class NetService {
  static Future<xml.XmlDocument?> getXml(String url, {int okCode = 200}) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == okCode) {
          return xml.XmlDocument.parse(response.body);
        }
        PrintService.showDataNotOK(response);
        return null;
      })
      .catchError((err) => PrintService.showError(err));
  }
}

Main主要的

import 'dart:async';
import 'dart:math';

import 'package:_samples2/networking.dart';
import 'package:xml/xml.dart' as xml;


class HindustanTimes {
  var newsFeeds = <MapEntry<String, String>>[];

  FutureOr<void> fetchRssAvailable() async {
    final url = 'https://www.hindustantimes.com/rss';
    var regExp = RegExp(r'<a title="(.+)" href="(.+)">');
    var rawPage = await NetService.getRaw(url).whenComplete(() => print('Feeds Page received.'));
    var matches = regExp.allMatches(rawPage ?? '');

    newsFeeds = matches.map((e) => MapEntry(e.group(1)!, e.group(2)!)).toList();
    print('${newsFeeds.length} feed(s) found.\n');
  }

  FutureOr<void> fetchNewsFeed({int? index}) async {
    var idx = index != null && index < newsFeeds.length 
      ? index
      : Random().nextInt(newsFeeds.length);

    await NetService.getXml(newsFeeds[idx].value)
      .then((xml.XmlDocument? document) {
        if (document != null) {
          var items = document.findAllElements('item');
          var titles = items.map((e) => e.getElement('title')!.text).toList();

          for (var i = 0; i < titles.length; i++) {
            print('[${i+1}] ${titles[i]}');
          }
        }
      })
      .whenComplete(() => print('\nNews Feed "${newsFeeds[idx].key}" received'));
  }
}

void main(List<String> args) async {
  var rss = HindustanTimes();
  await rss.fetchRssAvailable();
  await rss.fetchNewsFeed(index: 70);
  print('Done!');
}

Result:结果:

Feeds Page received.
145 feed(s) found.

[1] Horoscope Today: Astrological prediction for March 10
[2] Horoscope Today: Astrological prediction for March 9

News Feed "Horoscope" received
Done!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试使Restful Webservice及其客户端成为传递XML时遇到的问题 - I am trying to make Restful Webservice and it's client,facing issue while passing XML 我正在尝试从 Web API 应用程序(在 IIS 上发布)访问数据到控制台应用程序(VSExpress2013) - I am trying to access data from web API application(pulished at IIS) to console applicatication(VSExpress2013) 我在使用json codeigniter时遇到问题,请注意其未关闭标签 - i am having a issue with json codeigniter rest its not closing the tag 使用Spring Boot和Thymeleaf-我无法将数据从模板传递到控制器再传递回模板 - Using Spring Boot and Thymeleaf - I am having trouble passing data from template to controller back to template 我在 Mac 中使用 java 运行 curl 命令时遇到以下错误,它给出 IOException 并说无法运行程序 - I am having below error while running curl command using java in Mac where it gives IOException and says cannot run the program 我正在尝试从php $ _GET获取数据,然后使用rest api对其进行解析,但这会导致错误 - I am trying to get data from php $_GET then parse it using rest api, but it causes an error 我已经使用 REST API 调用建立了与 LinkedIn 的连接。 但是我在获取相关连接时遇到了这个问题 - I have established the connection to LinkedIn using REST API call. But I am facing the issue while fetching the related connections 使用 PATCH 修改 Firebase 实时数据库中的数据时出现问题 - Having issue with modifying data in Firebase realtime database using PATCH 我正在尝试使用HTTPClient发出简单的身份验证请求,但收到错误 - I am trying to make a simple authentication request using HTTPClient but am receiving an error 尝试使用 Python 通过 API 访问数据时出错 - Error when trying to access data via API using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM