首页 > 解决方案 > 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);
  }
}

标签: jsonflutterapihttpdart

解决方案


发生错误是因为您遍历地图并尝试获取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);
  }
}

推荐阅读