【发布时间】:2020-04-07 12:47:10
【问题描述】:
我的飞镖代码有问题。我正在尝试从 API 获取一些数据,它返回一个 JSON 数组。我创建了一个解析我的 JSON 的模型。之后,我尝试将获取的数据传递给我的函数,但出现此错误:“无法从函数 'fetchCountries' 返回类型为 'List 的值,因为它的返回类型为 'Future'”。
有人知道吗?
国家模式
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')
}
}
【问题讨论】:
-
您的错误消息中有修复:删除
Future。返回Country -
但是我怎样才能从 API 中获取数据呢?
-
fetchCountries的返回类型应该是Future<List<Country>>。
标签: dart