我有來自 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}]}
錯誤:未處理的例外:“List”型別不是“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"]
);
}
}
嘗試使用這樣的 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);
});
}
錯誤:
未處理的例外:“List”型別不是“List<Map<String, dynamic>>”型別的子型別
它指向 Game 類中的這一行:
gameQuestions : Question.listFromJson(parsedJson['game_questions']),
有什么建議嗎?
uj5u.com熱心網友回復:
嘗試這個,
Question.listFromJson(List<Map<String,dynamic>>.from(parsedJson['game_questions'])),
uj5u.com熱心網友回復:
我們可以通過修改類的static建構式來解決這個問題Question:
static listFromJson(List< dynamic> list) { // change
List<Question> questions = [];
for (var value in list) { questions.add(Question.fromJson(value)); }
return questions;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342557.html
