【问题标题】:Flutter Quiz Api tried calling []() NoSuchMethodErrorFlutter Quiz Api 尝试调用 []() NoSuchMethodError
【发布时间】: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


【解决方案1】:

发生错误是因为您遍历地图并尝试获取 question 但您的第一个键 response_code 没有此属性。除此之外,如果您迭代到第二个键results,它是List&lt;Map&lt;String, dynamic&gt;&gt; 类型,您无法检索带有括号['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);
  }
}

【讨论】:

  • 不太确定类型转换是否有效。由于 extractedData 来自 JSON 解析,因此从 extractedData['results'] 返回的类型最终将是 List&lt;dynamic&gt;
  • type 'List' 不是类型 'List>' 的子类型
  • 如果我将 List> 更改为 List 就可以了!谢谢
  • 不客气。您可以将我的答案标记为已被其他人接受吗?
猜你喜欢
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
相关资源
最近更新 更多