Ошибка при разборе данных из остальных API. Попытка вызова: cast‹Map‹String, dynamic››() Найдено: cast‹RK, RV›() =› Map‹RK, RV› во флаттере

Я пытаюсь разобрать данные из сети. Вот мой модельный класс-

import 'dart:convert';

class ModelEvent {
ModelEvent({
required this.id,
required this.appName,
required this.desc,
required this.colorValue,
required this.logoFileName,
required this.logoFilePath,
required this.splashScreenFileName,
required this.splashScreenFilePath,
required this.userId,
required this.createdAt,
required this.updatedAt,
required this.apptemplate,
});

final int id;
final String appName;
final String desc;
final String colorValue;
final String logoFileName;
final String logoFilePath;
final String splashScreenFileName;
final String splashScreenFilePath;
final String userId;
final DateTime createdAt;
final DateTime updatedAt;
final Apptemplate? apptemplate;

factory ModelEvent.fromJson(String str) => ModelEvent.fromMap(json.decode(str));

String toJson() => json.encode(toMap());


factory ModelEvent.fromMap(Map<String, dynamic> json) => ModelEvent(
id: json["id"],
appName: json["app_name"],
desc: json["desc"],
colorValue: json["color_value"],
logoFileName: json["logo_file_name"],
logoFilePath: json["logo_file_path"],
splashScreenFileName: json["splash_screen_file_name"],
splashScreenFilePath: json["splash_screen_file_path"],
userId: json["user_id"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
apptemplate: json["apptemplate"] == null ? null : 
Apptemplate.fromMap(json["apptemplate"]),
);

Map<String, dynamic> toMap() => {
"id": id,
"app_name": appName,
"desc": desc,
"color_value": colorValue,
"logo_file_name": logoFileName,
"logo_file_path": logoFilePath,
"splash_screen_file_name": splashScreenFileName,
"splash_screen_file_path": splashScreenFilePath,
"user_id": userId,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"apptemplate": apptemplate == null ? null : apptemplate!.toMap(),
};
}

class Apptemplate {
Apptemplate({
required this.template,
required this.appinfoId,
});

final String template;
final String appinfoId;

factory Apptemplate.fromJson(String str) => Apptemplate.fromMap(json.decode(str));

String toJson() => json.encode(toMap());

factory Apptemplate.fromMap(Map<String, dynamic> json) => Apptemplate(
template: json["template"],
appinfoId: json["appinfo_id"],
);

Map<String, dynamic> toMap() => {
"template": template,
"appinfo_id": appinfoId,
};
}

А методы -

List<ModelEvent> parseEvents(String responseBody) { //calling this method shows the error
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();

return parsed.map<ModelEvent>((json) => ModelEvent.fromJson(json)).toList();

}

Future<List<ModelEvent>> fetchEvents(http.Client client) async {
final response =
await http.post(Uri.parse(url),
    headers:{
  'Authorization': 'Bearer $token',
}
);
print(response.statusCode);
if (response.statusCode == 200) {
  this.setState(() {
    eventList = parseEvents(response.body);
  });

  return parseEvents(response.body);
} else {
  //If the server did not return a 200 OK response,
  // then throw an exception.
  throw Exception('Failed to load');
}

В консоли написано: «Необработанное исключение: NoSuchMethodError: класс '_InternalLinkedHashMap‹String, dynamic›» не имеет метода экземпляра 'cast' с соответствующими аргументами. а также Пробовал вызывать: cast‹Map‹String, dynamic››() Найдено: cast‹RK, RV›() =› Map‹RK, RV› Вот образ консоли- Image


person Himel    schedule 07.06.2021    source источник


Ответы (1)


попробуй это Map<String, dynamic> parsed = jsonDecode(responseBody);

person Giorgi    schedule 07.06.2021
comment
А как вернуть в виде списка объектов? Должен ли я писать новый метод? - person Himel; 07.06.2021
comment
как это было раньше - person Giorgi; 07.06.2021