How to convert list getting from future method to Map<String, dynamic>
428
Change List<Map>
by List<Map<String, dynamic>>
static List<Map<String, dynamic>> convertToMap({List myList }) {
List<Map<String, dynamic>> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}
Author by
Mahmoud Metawee
Updated on December 27, 2022Comments
-
Mahmoud Metawee over 1 year
I want to convert the list coming from
getPosts
method (getting result from the web json and stored in the posts list) to ListPost Class
class Post { final int userId; final String id; final String title; final String body; Post(this.userId, this.id, this.title, this.body); }
Future<List<Post>> getPosts() async { var data = await http .get("https://jsonplaceholder.typicode.com/posts"); var jasonData = json.decode(data.body); List<Post> posts = []; for (var i in jasonData) { Post post = Post(i["userId"], i["id"], i["title"], i["body"]); posts.add(post); } return posts; }
I tried to put the result directly to this method
static List<Map> convertToMap({List myList }) { List<Map> steps = []; myList.forEach((var value) { Map step = value.toMap(); steps.add(step); }); return steps; }
but it's not working, I see this error
The argument type 'List<Map<dynamic, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.
-
lsaudon about 3 yearsWhy put it in a map list?
-
Mahmoud Metawee about 3 years@lsaudon I wanna store it to push it to firestore collection, it's need to be
Map<String, dynamic>
-
nvoigt about 3 yearsPlease post a minimal reproducible example.
-
lsaudon about 3 yearsI don't think you should do it by hand. Look pub.dev/packages/json_serializable
-
lsaudon about 3 years
id
isint
not aString
-
Mahmoud Metawee about 3 years@lsaudon I tried your method but I think the issue is with Future, I see this
The argument type 'Future<List<Post>>' can't be assigned to the parameter type 'List<dynamic>'.
-
Mahmoud Metawee about 3 years@lsaudon I'll try this library thank you
-
nvoigt about 3 yearsThis is not a minimal reproducible example. You said you want to do X, yet in your code I see no attempt to do X. You have not even posted the lines where you do what you want to do. Where the error supposedly occurs. We cannot help you by speculating what code you may have written and then telling you what errors you may have made in that code we think you maybe wrote. Please post a fully working example that demonstrates the error you get.
-