我每次调用api时,我的代码都会以某种方式返回此错误。
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'String' is not a subtype of type 'int'
昨天还好。我的Api电话总会发出。现在,每当我调用api时,该消息始终会发出。这是我的代码
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _isLoading = false;
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(countryController.text).then((newData) {
setState(() {
data = newData;
_isLoading = false;
});
});
}),
],
),
_isLoading ? CircularProgressIndicator()
:
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Card(
child: ListTile(
title: Text(data[index].date.toString()),
subtitle: Text(data[index].cases.toString()),
onTap: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Information()))
},
),
);
},
itemCount: data.length,
),
),
],
));
}
}
这是未来。
//The Api call
Future <List<Data>> fetchData(String countryName) async {
setState(() {
_isLoading = true;
});
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
json.decode(response.body).forEach((item){
data.add(Data.fromJson(item));
});
return data;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load data');
}
}
类构造器
class Data {
final int date;
final String country;
final int 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['Confirmed']);
}
}
我尝试了很多事情,但到目前为止,仍然没有任何效果。可以帮我吗?
答案 0 :(得分:2)
问题是由数据模型中的日期字段引起的,从API返回的值是String,数据模型中描述的类型是int,从而导致类型转换问题,请按以下方式更新数据模型:
priceData1 == priceData2
答案 1 :(得分:1)
我认为API的响应存在一些问题。因此,一旦尝试更改您的类构造函数代码,如下所示。希望对您有帮助。
class Data {
final String date;
final String country;
final int 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['Confirmed']);
}
}
答案 2 :(得分:1)
我不知道您使用的api是否更改了格式,但现在日期的类型为字符串
[
{
"Country": "Malaysia",
"CountryCode": "MY",
"Province": "",
"City": "",
"CityCode": "",
"Lat": "4.21",
"Lon": "101.98",
"Confirmed": 4683,
"Deaths": 76,
"Recovered": 2108,
"Active": 2499,
"Date": "2020-04-13T00:00:00Z" //Is a String now
},
...
因此,您必须将模型参数更新为字符串
final String date;