【发布时间】:2020-10-18 17:51:38
【问题描述】:
我正在为我的班级构建一个关于冠状病毒追踪器的项目。每次我尝试调用 api 并点击 serach 图标时,它都会在控制台中引发错误。我尝试了很多东西,但它抛出了同样的错误。谁能帮忙弄清楚代码有什么问题?
class _HomePageState extends State<HomePage> {
List <Data> data = [];
var countryController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text('CoronaVirus Tracker')),
),
body: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: TextField(
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Enter a Country'),
controller: countryController,
),
),
IconButton(
icon: Icon(Icons.search),
color: Colors.blue,
onPressed: () {
fetchData().then((newData) {
setState(() {
data = newData as List<Data>;
});
});
}),
],
),
//The search item appear here
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
title: Text(data[index].country),
subtitle: Text(data[index].cases),
onTap: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Text('This is a new page!!')))
},
),
);
},
itemCount: data.length,
),
),
],
));
}
这里是 Api 代码
Future <Data> fetchData() async {
final response = await http.get('https://api.covid19api.com/live/country/malaysia/status/confirmed');
if (response.statusCode == 200) {
print(response.body);
// Transform json into object
return Data.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load data');
}
}
}
这里是构造函数
class Data {
final String date;
final String country;
final String cases;
Data({this.date, this.country, this.cases});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
country: json['Country'],
date: json['Date'],
cases: json['Cases']);
}
}
【问题讨论】:
-
欢迎使用 Stackoverflow :)... 有什么错误?
标签: flutter flutter-layout flutter-dependencies