Dart 类型为'的值;列表<;国家>;can';不能从函数'返回;国家和地区';因为它的返回类型为';未来<;国家>';

Dart 类型为'的值;列表<;国家>;can';不能从函数'返回;国家和地区';因为它的返回类型为';未来<;国家>';,dart,Dart,我的dart代码有问题。我试图从API获取一些数据,它返回一个JSON数组。我创建了一个解析JSON的模型。之后,我尝试将我获取的数据传递给我的函数,但出现了此错误:“无法从函数'fetchCountries'返回'List'类型的值,因为它的返回类型为'Future' 有人有线索吗 国家模式 导入'dart:convert'; List countryFromJson(String str)=>List.from(json.decode(str.map)(x)=>Country.fromJso

我的dart代码有问题。我试图从API获取一些数据,它返回一个JSON数组。我创建了一个解析JSON的模型。之后,我尝试将我获取的数据传递给我的函数,但出现了此错误:“无法从函数'fetchCountries'返回'List'类型的值,因为它的返回类型为'Future'

有人有线索吗

国家模式
导入'dart:convert';
List countryFromJson(String str)=>List.from(json.decode(str.map)(x)=>Country.fromJson(x));
阶级国家{
弦国;
int案例;
今日个案;;
死亡人数;
int今日死亡人数;
int恢复;
int-active;
int临界;
内特卡斯珀隆埃米利昂;
因特·埃米利昂;
综合测试;
int testsperonemilion;
国家({
这个国家,
这种情况,
这是今天的情况,
这就是死亡,
这就是今天的死亡,
这个,恢复了,,
这个,主动,,
这很关键,,
这个,凯斯伯伦·埃米利昂,
这个,死亡之星艾米利昂,
这个,这个测试,,
这是我的朋友,
});
工厂国家。fromJson(映射json)=>国家(
国家:json[“国家”],
案例:json[“案例”],
todayCases:json[“todayCases”],
死亡:json[“死亡”],
今日死亡:json[“今日死亡”],
已恢复:json[“已恢复”],
活动:json[“活动”],
关键:json[“关键”],
casesPerOneMillion:json[“casesPerOneMillion”],
死亡之声:json[“死亡之声”],
totalTests:json[“totalTests”],
testsPerOneMillion:json[“testsPerOneMillion”],
);
}
国家服务
导入'dart:async';
将“package:http/http.dart”导入为http;
导入“../models/country.dart”;
Future fetchCountries()异步{
最终响应=等待http.get('https://coronavirus-19-api.herokuapp.com/countries');
如果(response.statusCode==200){
返回countryFromJson(response.body);
}
否则{
抛出异常('加载国家/地区失败')
}
}


根据函数定义,您应该

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')
  }
}
Future fetchCountries()异步{
最终响应=等待http.get('https://coronavirus-19-api.herokuapp.com/countries');
如果(response.statusCode==200){
返回countryFromJson(response.body);
}
否则{
抛出异常('加载国家/地区失败')
}
}
所以你应该等待一个国家的名单,而不是一个国家。
希望有帮助

根据您的函数定义,您应该

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')
  }
}
Future fetchCountries()异步{
最终响应=等待http.get('https://coronavirus-19-api.herokuapp.com/countries');
如果(response.statusCode==200){
返回countryFromJson(response.body);
}
否则{
抛出异常('加载国家/地区失败')
}
}
所以你应该等待一个国家的名单,而不是一个国家。
希望有帮助

您的错误消息中有修复程序:删除
将来的
。返回
Country
但如何才能从API中提取数据?
fetchCountries
的返回类型应为
Future
。错误消息中有修复方法:删除
Future
。Return
Country
但是我如何才能从API中获取数据呢?
fetchCountries
的返回类型应该是
Future