Issue
im new in flutter , and i want to display my data from api json to my app with ResteApi , i made a model like that :
class Todo {
final int id;
final String title;
final bool completed;
Todo({required this.id, required this.title, required this.completed});
factory Todo.fromJson(Map<String, dynamic> json) {
return Todo(
id: json["id"] as int,
title: json["title"] as String,
completed: json["completed"] as bool);
}
Map<String, dynamic> toJson() => {'title': title, 'completed': completed};
@override
String toString() {
return 'Todo{id: $id, title: $title, completed: $completed}';
}
}
And a methode get in service class Like that :
final String apiUrl = "https://jsonplaceholder.typicode.com/todos";
Future<List<Todo>> getCases() async {
Response res = await get(Uri.parse(apiUrl));
if (res.statusCode == 200) {
List<dynamic> body = jsonDecode(res.body);
List<Todo> todo = body.map((dynamic item) => todo.fromJson(item)).toList();
return todo;
} else {
throw "Failed to load cases list";
}
}
but this errors it display to me:
A value of type 'List<dynamic>' can't be assigned to a variable of type 'List<Todo>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Todo>'
how can i fix it
Solution
There is a typo todo.fromJson
, it will be Todo.fromJson
List<Todo> todo = body.map((dynamic item) => Todo.fromJson(item)).toList();
Also it is better to accept null data
List<dynamic>? body = jsonDecode(res.body);
final todo =
body?.map((dynamic item) => Todo.fromJson(item)).toList() ?? [];
return todo;
Answered By - Yeasin Sheikh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.