首页 > 解决方案 > NoSuchMethodError:类'列表' 没有实例获取器 'country'

问题描述

我正在编写一个非常简单的应用程序来从 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"],
    );
}

标签: flutterdart

解决方案


您的 API 返回一个Future集合,即Future<List>在您收到的内容中FutureBuildersnapshot.data您收到的正是您从 API 中返回的内容,FutureList<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
                    );
                  },
                );
              }

推荐阅读