Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter _TypeError type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>

Tags:

flutter

dart

I am facing a strange error in flutter. I am using json serialisable.

Here is my code

class DivMatches{
  final List<Match> matches;
   DivMatches(this.matches);
  factory DivMatches.fromJson(Map<String, dynamic> json) =>
  _$DivMatchesFromJson(json);
  Map<String, dynamic> toJson() => _$DivMatchesToJson(this);

}

My web api sends data like this

[
 [
   {..},
   {..},
   {..},
   {..}
 ],
[...],
[...],
[...],
[...],
[...],
[...]
]

It's array of array.

Code that is generating error is

data = body.map((el) => DivMatches.fromJson(el)).toList(); 

error it gives

Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

Here is the screenshot enter image description here

JSON DATA here is the screenshots of json data formate

enter image description here

enter image description here

like image 388
Hkm Sadek Avatar asked Mar 04 '23 04:03

Hkm Sadek


2 Answers

Change this line :

final body = json.decode(res.body);

To this:

final body = json.decode(res.body) as List;

And this:

List<DivMatches> data = [];

body.forEach((el) {
   final List<Match> sublist = el.map((val) => Match.fromJson(val)).toList();
   data.add(DivMatches(sublist));
}); 

Note: check if your Match.fromJson returns a Match object or Map.

like image 139
diegoveloper Avatar answered Mar 06 '23 16:03

diegoveloper


You can use cast<Type>():

import 'dart:convert';

void main() {
  print(getScores());
}

class Score {
  int score;
  Score({this.score});

  factory Score.fromJson(Map<String, dynamic> json) {
    return Score(score: json['score']);
  }
}

List<Score> getScores() {
  var jsonString = '''
  [
    {"score": 40},
    {"score": 80}
  ]
''';

  List<Score> scores = jsonDecode(jsonString)
      .map((item) => Score.fromJson(item))
      .toList()
      .cast<Score>(); // Solve Unhandled exception: type 'List<dynamic>' is not a subtype of type 'List<Score>'

  return scores;
}


like image 40
Omar Makled Avatar answered Mar 06 '23 16:03

Omar Makled