繁体   English   中英

在应用程序中显示从 JSON API 获取的数据

[英]Display data fetched from JSON API in app

我正在开发一个股票应用程序,我必须在其中显示与股票相关的新闻。 我创建了一个新闻类以及一个工厂构造函数来转换来自 json 的数据

class News {
  final String title;
  final String desc;
  final String imgURL;
  final String url;

  News(
      {required this.title,
      required this.desc,
      required this.imgURL,
      required this.url});

  factory News.fromJSON(Map<String, dynamic> json) {
    final title = json["title"] as String;
    final desc = json["description"] as String;
    final imgUrl = json["image_url"] as String;
    final url = json["url"] as String;
    return News(title: title, desc: desc, imgURL: imgUrl, url: url);
  }
}

我已经制定了一种从 API 获取数据的方法:

Future getNews() async {
    final response = await http.get(Uri.parse(
        'https://api.stockdata.org/v1/news/all?&filter_entities=true&language=en&api_token=${api_token}&countries=${country}'));
    if (response.statusCode == 200) {
      final jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => News.fromJSON(data));
    } else {
      throw Exception('Unexpected error occurred!');
    }
  }

我无法理解如何在我的应用程序中显示数据。 我尝试使用 FutureBuilder,但我似乎无法理解它是如何工作的。 任何帮助,将不胜感激!

对于 FutureBuilder,您可以这样做:

      FutureBuilder(
        future: getNews(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if(snapshot.hasData){
            // Save your data in a variable
            List<News> news = snapshot.data;
            // Create a listview to show all of the news
            return newsListView(news); //This is a list
          } else {
            return Center(
              child: Container(
                width: 300,
                height: 290,
                child: Center(child: Text("Error"))
              )
            );
          }
        }
      ),

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM