1

I am beginner in Dart. Following is an array and I need to access a specific element

'text': 'Rabbit'and 'score': 3

I tried the below:

_questions[1]['answers'][0]['text']['score'] 

This doesn't work.

var _questions = [
{
  'question': 'What is your color?',
  'answers': [
    {'text': 'Black', 'score': 10},
    {'text': 'Red', 'score': 5},
    {'text': 'Green', 'score': 3},
    {'text': 'White', 'score': 1},
  ],
},
{
  'question': 'What is your animal?',
  'answers': [
    {'text': 'Rabbit', 'score': 3},
    {'text': 'Snake', 'score': 11},
    {'text': 'Elephant', 'score': 5},
    {'text': 'Lion', 'score': 9},
  ],
},
];

1 Answer 1

1

(disclaimer: I don't know Dart!) I've played a bit with the code using dartpad.dartlang.org:

Cast the answer object as List:

var answers = (_questions[1]['answers'] as List);

And then you can the first object data as:

answers[0]['text']
answers[0]['score']
Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't work. It gives the error: The operator '[]' isn't defined for the class 'Object'.
Thanks Luis. This works... so it means the child cannot be accessed directly.
Great. May be it can be accessed but I don’t know enough Dart to be sure about it. Please remember to accept the answer.

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.