Ad

Flutter Quiz Api Tried Calling []() NoSuchMethodError

- 1 answer

I cant get data from the API.

I want to fetch the question String from the JSON but it throws an error

ERROR:

I/flutter ( 6609): NoSuchMethodError: Class 'int' has no instance method '[]'.

I/flutter ( 6609): Receiver: 0

I/flutter ( 6609): Tried calling: [] ("question")

MY 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"
         ]
      }
   ]
}

My Method:

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);
  }
}
Ad

Answer

The error occurs because you iterate through your map and tried to get question but your first key response_code doesn't have this property. beside if you iterate to your second key results it is a of type List<Map<String, dynamic>> where you can't retrieve the questions with the bracket ['question'] since it is a List. To fix this you have to get the results first and then iterate through it.

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);
  }
}
Ad
source: stackoverflow.com
Ad