NoSuchMethodError:类“ List <Country>”没有实例获取程序“ country”

时间:2020-04-07 14:30:50

标签: flutter dart

我正在编写一个非常简单的应用程序,以从API下载一些数据。但是,API返回JSON数组。我试图解析此JSON数组,但是不幸的是我没有正确地执行它,程序返回了错误。有什么办法可以解决吗?有谁可以帮助我吗?

国家/地区视图

import 'package:flutter/material.dart';
import '../../models/country.dart';
import '../../data/countries_service.dart';

class CountriesScreenAndroid extends StatefulWidget {
  @override
  _CountriesScreenAndroidState createState() => _CountriesScreenAndroidState();
}

class _CountriesScreenAndroidState extends State<CountriesScreenAndroid> {
  Future<List<Country>> futureCountries;

  @override
  void initState() {
    super.initState();
    futureCountries = fetchCountries();
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: FutureBuilder(
        future: futureCountries,
        builder: (context, snapshot) {

          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(snapshot.data.country[index]), // Here is the problem
                );
              },
            );
          }

          return Center(
            child: CircularProgressIndicator()
          );
        },
      )
    );
  }
}

国家服务

import 'dart:async';
import 'package:http/http.dart' as http;
import '../models/country.dart';

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

国家/地区模型

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"],
    );
}

1 个答案:

答案 0 :(得分:0)

您的API返回一个Future集合,即Future<List>,因此在您的FutureBuilder中,您收到的snapshot.data就是您从Future内部的API返回的内容即List<Country>。因此,您可以按以下方式更改代码:

             if (snapshot.hasData) {
                final countries = snapshot.data;
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(countries[index].country), // Here was the problem
                    );
                  },
                );
              }