我的飞镖代码有问题。我正在尝试从API提取一些数据,它返回JSON数组。我创建了一个解析JSON的模型。之后,我尝试将获取的数据传递给我的函数,但出现此错误:“无法从函数'fetchCountries'返回'列表类型的值,因为它的返回类型为'未来'”。 / p>
有人知道吗?
import 'dart:convert';
List<Country> countryFromJson(String str) => List<Country>.from(json.decode(str).map((x) => Country.fromJson(x)));
class Country {
String country;
int cases;
int todayCases;
int deaths;
int todayDeaths;
int recovered;
int active;
int critical;
int casesPerOneMillion;
int deathsPerOneMillion;
int totalTests;
int testsPerOneMillion;
Country({
this.country,
this.cases,
this.todayCases,
this.deaths,
this.todayDeaths,
this.recovered,
this.active,
this.critical,
this.casesPerOneMillion,
this.deathsPerOneMillion,
this.totalTests,
this.testsPerOneMillion,
});
factory Country.fromJson(Map<String, dynamic> json) => Country(
country: json["country"],
cases: json["cases"],
todayCases: json["todayCases"],
deaths: json["deaths"],
todayDeaths: json["todayDeaths"],
recovered: json["recovered"],
active: json["active"],
critical: json["critical"],
casesPerOneMillion: json["casesPerOneMillion"],
deathsPerOneMillion: json["deathsPerOneMillion"],
totalTests: json["totalTests"],
testsPerOneMillion: json["testsPerOneMillion"],
);
}
import 'dart:async';
import 'package:http/http.dart' as http;
import '../models/country.dart';
Future<Country> fetchCountries() async {
final response = await http.get('https://coronavirus-19-api.herokuapp.com/countries');
if(response.statusCode == 200) {
return countryFromJson(response.body);
}
else {
throw Exception('Failed to load Country')
}
}
答案 0 :(得分:2)
在函数定义中,您应该拥有
Future<List<Country>> fetchCountries() async {
final response = await http.get('https://coronavirus-19-api.herokuapp.com/countries');
if(response.statusCode == 200) {
return countryFromJson(response.body);
}
else {
throw Exception('Failed to load Country')
}
}
因此,您应该等待一个国家/地区列表,而不是一个国家/地区。 希望对您有帮助!