【发布时间】:2021-12-25 22:53:36
【问题描述】:
我无法从 API 获取数据。
我想从 JSON 中获取问题字符串,但它会引发错误
错误:
I/flutter ( 6609): NoSuchMethodError: Class 'int' has no instance method '[]'.
I/flutter ( 6609): Receiver: 0
I/flutter ( 6609): Tried calling: [] ("question")
我的 API:
{
"response_code":0,
"results":[
{
"category":"Entertainment: Video Games",
"type":"multiple",
"difficulty":"medium",
"question":"What's the famous line Vaas says in "Far Cry 3"?",
"correct_answer":"Did I ever tell you the definition of Insanity?",
"incorrect_answers":[
"Have I failed to entertain you?",
"You're my b*tch!",
"Maybe your best course...would be to tread lightly."
]
},
{
"category":"Entertainment: Video Games",
"type":"boolean",
"difficulty":"easy",
"question":""Half-Life 2" runs on the Source Engine.",
"correct_answer":"True",
"incorrect_answers":[
"False"
]
}
]
}
我的方法:
Future<void> showQuestions() async {
try {
final response = await http
.get(Uri.parse('https://opentdb.com/api.php?amount=2'));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
extractedData.forEach((id, data) {
print(data["question"]);
});
}catch (err) {
print(err);
}
}
【问题讨论】:
-
好像您忘记进入 JSON 的
results部分。 -
如果我在没有 ["question"] 的情况下打印(数据)然后我得到结果,但我只想要问题
-
是的,但是您没有遍历正确的数据结构。您需要遍历 JSON 中的“结果”。现在,您正在遍历包含“response_code”和“results”的 JSON 的根。
-
好吧,我明白了,但我如何遍历 JSON,我通常在 firebase 上做数据 [“question”],但这里有点不同。
标签: json flutter api http dart