Home > Software design >  Unhandled Exception: type List<dynamic> is not a subtype of type List<Map<String, dynami
Unhandled Exception: type List<dynamic> is not a subtype of type List<Map<String, dynami

Time:10-31

I have this response text from API. When I try to create a new Game from this response I get an error :

response : {success: true, games: [{game_id: 3, game_gide: {0: b, 1: , 2: , 3: a, 11: b, 14: e}, game_cells: [3,8,23,18,2,7,17,22,1,6,16,21], game_questions: [{title: question 2 h, answer: abcde, isTrue: false}, {title: question 1 h, answer: xxxxx, isTrue: false}]}

ERROR : Unhandled Exception: type 'List' is not a subtype of type 'List<Map<String, dynamic>>'

class Game {
  String gameId;
  String gameLevel;
  List<int> gameCells;
  List<Question> gameQuestions;


  Game({
    this.gameId,
    this.gameLevel,
    this.gameCells,
    this.gameQuestions,
  });

  static fromJson(Map<String, dynamic> parsedJson){
    print(parsedJson['game_vertical_questions']);
    return Game(
        gameId: parsedJson['game_id'],
        gameLevel: parsedJson['game_level'],
        gameCells: (jsonDecode(parsedJson['game_cells']) as List<dynamic>).cast<int>(),
        gameQuestions : Question.listFromJson(parsedJson['game_questions']),
    );
  }
}




class Question {
  String title;
  String answer;
  bool isTrue;

  Question({ this.title, this.answer, this.isTrue});

  static listFromJson(List<Map<String, dynamic>> list) {
    List<Question> questions = [];
    for (var value in list) { questions.add(Question.fromJson(value)); }
    return questions;
  }

  static fromJson(Map<String, dynamic> parsedJson){
    return Question(
        title: parsedJson["title"],
        answer: parsedJson["answer"],
        isTrue: parsedJson["isTrue"]
    );
  }
}

I get the error when trying to use the JSON text like this:

var jsonData = json.decode(response.body);
var res = jsonData["games"];
for (var g in res){
  //print(g);
  Game game = Game.fromJson(g);
  setState(() {
    gamesList.add(game);
  });
}

error:

Unhandled Exception: type 'List' is not a subtype of type 'List<Map<String, dynamic>>'

It points to this line in Game class:

gameQuestions : Question.listFromJson(parsedJson['game_questions']),

any suggestion ?

CodePudding user response:

Try this,

Question.listFromJson(List<Map<String,dynamic>>.from(parsedJson['game_questions'])),

CodePudding user response:

We can solve the issue by modifying the static constructor of the Question class:

static listFromJson(List< dynamic> list) { // change
  List<Question> questions = [];
  for (var value in list) { questions.add(Question.fromJson(value)); }
  return questions;
}
  • Related