Mahmoud Metawee
Mahmoud Metawee

Reputation: 204

How to convert list getting from future method to Map<String, dynamic>

I want to convert the list coming from getPosts method (getting result from the web json and stored in the posts list) to List

Post 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>'.

Upvotes: 0

Views: 754

Answers (1)

lsaudon
lsaudon

Reputation: 1458

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;
  }

Upvotes: 1

Related Questions