简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM