json - Flutter Quiz Api 尝试调用 []() NoSuchMethodError
问题描述
我无法从 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);
}
}
解决方案
发生错误是因为您遍历地图并尝试获取question
但您的第一个键response_code
没有此属性。除此之外,如果您迭代到第二个键results
,它是一种类型List<Map<String, dynamic>>
,您无法用括号检索问题,['question']
因为它是List
. 要解决此问题,您必须获取第results
一个,然后对其进行迭代。
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>;
final List<dynamic> results = extractedData['results'];
for (final result in results) {
print(result['question']);
}
} catch (err) {
print(err);
}
}
推荐阅读
- python - django:redis:CommandError: You have not set ASGI_APPLICATION, 这是运行服务器所需要的
- wordpress - 需要 Nginx 专家(Wordpress 插件问题)
- jenkins - Jenkins管道环境变量否定
- python - os.listdir() 找不到在 subprocess.run 中创建的文件
- sql - AND NOT LIKE 语句与 IN 子句一起使用?
- .net - 当我在 Visual Basic 中更新其他字段时,如何保持 SQL tble 字段不更新?
- c++ - 如果矩阵大小增加,使用 c++ eigen 包的矩阵乘法似乎不稳定
- python - 使用 python 从 mongoDB 获取 3 天的数据
- c# - 更改通用列表字段中的类型<>
- youtube - 在 Nativescript 中播放 Youtube 视频