I am building a project about coronavirus tracker for my class. Everytime I tried to call the api and hit the serach icon it throw an error in the console. I have tried many things but it throw the same error. can anyone help figure out what is wrong with code?
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,
),
),
],
));
}
Here is the Api code
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');
}
}
}
Here is the constructor
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']);
}
}