Home > Mobile >  Dart Json object access
Dart Json object access

Time:09-06

I am trying to fetch dynamic json objects that have the following form:

    [
       {
        "id" : 1,
        "date" : "2022-01-01",
        "name" : "name",
       },
       {
       "id" : 2,
       "date" : "2022-01-02",
       "name" : "name2",
        }
    ]

When i am going to show the result, i get the following error: type 'List' is not a subtype of type 'Map<String, dynamic>'

The code i use:

class Post {
  final int? id;
  final DateTime? date;
  final String? name;

  Post({
    required this.id,
    required this.date,
    required this.name,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      date: json['date'],
      name: json['name'],
    );
  }
}

Future<Post> fetchPost() async {
  final response = await http.get(
    Uri.parse('http i work on'),
    headers: {
      'Accept': 'accept',
      'access_token': 'access_token',
    },
  );

  final jsonResponse = jsonDecode(response.body);
  if (response.statusCode == 200) {
    return Post.fromJson(jsonResponse);
  } else {
    throw Exception('Failed to load post');
  }
}

I am trying to convert Map to List but i keep on failing. Is this my mistake or it's something else? Why those [ ] are around the objects?

CodePudding user response:

jsonResponse is List<Map<String, dynamic>> but your treat with like Map, so try this:

if (response.statusCode == 200) {
    final jsonResponse = jsonDecode(response.body);
    
    return jsonResponse.map((e) => Post.fromJson(e)).toList();
  } else {
    throw Exception('Failed to load post');
  }

and also change fetchPost() return type like this:

Future<List<Post>> fetchPost() async {
...
}
  • Related