【发布时间】:2021-10-26 04:21:57
【问题描述】:
我正在开发一个股票应用程序,我必须在其中显示与股票相关的新闻。我为它创建了一个 News 类以及一个工厂构造函数来转换来自 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,但我似乎无法理解它是如何工作的。 任何帮助将不胜感激!
【问题讨论】:
-
@abhi 希望你是新来的。请在发布您的问题之前进行一些研究。在没有太多研究的情况下发布问题可能会导致对您的问题投反对票。参考这个flutter.dev/docs/cookbook/networking/fetch-data
-
非常感谢