gpt4 book ai didi

dart - 从函数 'List can'返回类型 'fetchCountries' t的值,因为它的返回类型为 'Future'

转载 作者:行者123 更新时间:2023-12-03 04:23:43 24 4
gpt4 key购买 nike

我的 Dart 代码有问题。我正在尝试从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')
}
}

enter image description here

enter image description here

最佳答案

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

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')
}
}

因此,您应该等待一个国家/地区列表,而不是一个国家/地区。
希望能帮助到你!

关于dart - 从函数 'List<Country> can'返回类型 'fetchCountries' t的值,因为它的返回类型为 'Future<Country>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com