当前位置: 首页 > 知识库问答 >
问题:

未处理的异常:类型列表不是类型列表的子类型

江烨伟
2023-03-14

我有来自API的响应文本。当我试图创建一个新的游戏从这个响应我得到一个错误:

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

错误:未处理的异常:“列表”类型不是“列表”类型的子类型

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"]
    );
  }
}

我在尝试使用JSON文本时遇到如下错误:

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

错误:

未处理的异常:“列表”类型不是“列表”类型的子类型

它指向游戏类中的这一行:

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

有什么建议吗?

共有2个答案

裘安阳
2023-03-14

我们可以通过修改问题类的静态构造函数来解决此问题:

static listFromJson(List< dynamic> list) { // change
  List<Question> questions = [];
  for (var value in list) { questions.add(Question.fromJson(value)); }
  return questions;
}
马欣荣
2023-03-14

试试这个,

问题。listFromJson(列表

 类似资料: