【问题标题】:A value of type 'List<Country> can't be returned from function 'fetchCountries' because it has a return type of 'Future<Country>'无法从函数“fetchCountries”返回类型为“List<Country>”的值,因为它的返回类型为“Future<Country>”
【发布时间】: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&lt;List&lt;Country&gt;&gt;

标签: dart


【解决方案1】:

根据你的函数定义,你应该有

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

因此,您应该等待国家/地区列表,而不是单个国家/地区。 希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 2021-09-27
    • 2022-10-12
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多