简体   繁体   中英

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

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 ?

尝试这个,

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

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

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