【发布时间】:2020-04-07 14:30:50
【问题描述】:
我正在编写一个非常简单的应用程序来从 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"],
);
}
【问题讨论】:
-
将
title: Text(snapshot.data.country[index])更改为title: Text(snapshot.data[index].country)