0

I´m trying to acess the score of a given question:

 main() {
      final questions = const [
        {
          "question": "Your favorite animal?",
          "answer": [
            {"text": "Lion", "score": 4},
            {"text": "Tiger", "score": 6},
          ]
        }
      ];
    
      print(questions[0]["answer"]["score"]);
    }

Here´s how i´m trying to acess it: print(questions[0]["answer"]["score"]);

But it´s showing me an error:

Error: The operator '[]' isn't defined for the class 'Object?'.
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '[]' operator.
  print(questions[0]["answer"]["pontuacao"]);

How can I fix this?

1
  • questions[0]["answer"] gives you a list of elements, you need to index into it before calling ["score"]. Commented Dec 18, 2022 at 20:48

1 Answer 1

2

Until questions[0]["answer"] it's ok. But then, that returns an array, in particular:

[
  {"text": "Lion", "score": 4},
  {"text": "Tiger", "score": 6},
]

So, if you want to print a single score, just add an index like questions[0]["answer"][0]["score"]. Otherwise, if you want to print them all, just use

questions[0]["answer"].map((element) => print(element["score"])

If you want to print ALL questions's scores, do te same for questions array:

questions.map((question) => question["answer"].map((element) => print(element["score"]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for taking time to answer my question, this is exactly what i needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.