我试图显示来自API的信息列表。我已经分别创建了一个API和模型和提供程序类。当我试图访问API时,我得到了以下信息:
“List”不是类型“Map<String,dynamic>”的子类型”
其中我的API响应如下所示
[
{
"id": 1,
"username": "naveen",
"email": "[email protected]",
"scheduledDate": "15-09-2022",
"remarks": "demo",
"createdAt": "2022-09-14T23:57:09.344Z",
"updatedAt": "2022-09-14T23:57:09.344Z"
},
{
"id": 2,
"username": "naveen",
"email": "[email protected]",
"scheduledDate": "16-09-2022",
"remarks": "demo",
"createdAt": "2022-09-14T23:57:17.756Z",
"updatedAt": "2022-09-14T23:57:17.756Z"
}
]
字符串
我的模特课
class ScheduleListModel {
int? id;
String? username;
String? email;
String? scheduledDate;
String? remarks;
String? createdAt;
String? updatedAt;
ScheduleListModel(
{this.id,
this.username,
this.email,
this.scheduledDate,
this.remarks,
this.createdAt,
this.updatedAt});
ScheduleListModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
username = json['username'];
email = json['email'];
scheduledDate = json['scheduledDate'];
remarks = json['remarks'];
createdAt = json['createdAt'];
updatedAt = json['updatedAt'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['id'] = id;
data['username'] = username;
data['email'] = email;
data['scheduledDate'] = scheduledDate;
data['remarks'] = remarks;
data['createdAt'] = createdAt;
data['updatedAt'] = updatedAt;
return data;
}
}
型
提供程序类
class ScheduleListProvider extends ChangeNotifier {
bool isBack = false;
late ScheduleListModel scheduleListModel;
ScheduleListModel get getScheduleListModel => scheduleListModel;
Future<void> getAllScheduleListData() async {
getAllSchedule().then((response) => {
if (response!.statusCode == 200)
{
scheduleListModel =
ScheduleListModel.fromJson(json.decode(response.body)),
notifyListeners(),
}
});
}
}
型
这是我的API调用
Future<http.Response?> getAllSchedule() async {
late SharedPreferences logindata;
logindata = await SharedPreferences.getInstance();
late String? token = logindata.getString('token');
http.Response? response;
try {
response = await http.get(Uri.parse(Config.getAllScheduleAPI), headers: {
HttpHeaders.contentTypeHeader: "application/json",
'x-access-token': '$token',
});
} catch (e) {
log(e.toString());
}
return response;
}
型
当我尝试执行API调用时,我收到异常:
[错误:flutter/runtime/dart_vm_initializer.cc(41)]未处理的异常:类型'List'不是类型'Map<String,dynamic>'的子类型
帮我解决这个问题。
2条答案
按热度按时间7qhs6swi1#
您的API响应是
List<ScheduleListModel>
,而不是单个的ScheduleListModel。字符串
抛出此错误消息。根据您想要对列表执行的操作,您应该将
getAllScheduleListData()
更改为可以处理ScheduleListModel
列表的内容。wgx48brx2#
试试这个:
字符串