Home > database >  flutter error: The operator '[]' isn't defined for the class 'Object?
flutter error: The operator '[]' isn't defined for the class 'Object?

Time:12-19

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?

CodePudding user response:

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"]))

CodePudding user response:

Within your key questions, there's another list called answer.

You can't just access the index using []. You'll have to loop over it:

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


  for (var i = 0; i < questions.length; i  ) {
    print(questions[i]["question"]);
    print(questions[i]["answer"]);
  }
}
  • Related