0

I have a quick question and it's an easy one. Please somebody help.

I am an absolute beginner in flutter. I am having trouble accessing the object inside the list and their size. Here is a quick example of what I am trying to achieve.

final questions = [
    {
      'questionText': 'What's your favorite color?',
      'answers': [
        {'text': 'Black', 'score': 3},
        {'text': 'Blue', 'score': 1},
        {'text': 'White', 'score': 1}
      ]
    },
    {
      'questionText': 'What's your favorite animal?',
      'answers': [
        {'text': 'Lion', 'score': 3},
        {'text': 'Snake', 'score': 5},
        {'text': 'Cat', 'score': 1}
      ]
    },
    {
      'questionText': 'What's your favorite teacher?',
      'answers': [
        {'text': 'Ali', 'score': 3},
        {'text': 'Aslam', 'score': 3},
        {'text': 'Akram', 'score': 3}
      ]
    }
  ];


  print(questions.length);    // 3
  print(questions[0].length);    // 2
print(questions[0]['answers']);   //[{text: Black, score: 3}, {text: Blue, score: 1}, {text: White, score: 1}]

But when I tried to get the length of "answers" within the questions by following below method. I get this error (given inside comments).

print(questions[0]['answers'].length);  //Error: The getter 'length' isn't defined for the class 'Object'.

When I tried to print the first element of 'answers' array within the questions (which is "{'text': 'Black', 'score': 3}"), I get the below error

print(questions[0]['answers'][0]); // The method '[]' isn't defined for the class 'Object'

Also tried these

print(questions[0]['answers']['text']); // Error: The method '[]' isn't defined for the class 'Object'.
print(questions[0]['answers'[0]]);  // null
print(questions[0]['answers'['text']]); // Error: The argument type 'String' can't be assigned //to the parameter type 'int'.

How can I do this? Also, what should I do if I only want to print all three options('text') of 'answers'. I know it's a kinda dumb question but I am completely stuck here. Any help would highly be appreciated.

2 Answers 2

2

By the notation you're using Dart infers the types to a list of maps with string keys but mixed value types (questionText is string, answers is a list of maps again). That forces Dart to use Object as value type, what makes accessing nested fields impossible without casting.

questions[0].runtimeType // Type (_InternalLinkedHashMap<String, Object>)

You can also see that easily in the debugger by inspecting the questions object.

I suggest defining classes with properly typed properties.

class Question {
  Question(this.text, this.answers);

  final String text;

  final List<Answer> answers;

  String toString() => 'Question { text: $text, answers: $answers }';
}

class Answer {
  Answer(this.text, this.score);

  final String text;

  final int score;

  String toString() => 'Answer { text: $text, score: $score }';
}

main(List<String> args) {
  final questions = [
    Question('What\'s your favorite color?', [
      Answer('Black', 3),
      Answer('Blue', 1),
      Answer('White', 1),
    ]),
    Question('What\'s your favorite animal?', [
      Answer('Lion', 3),
      Answer('Snake', 5),
      Answer('Cat', 1),
    ]),
    Question('What\'s your favorite teacher?', [
      Answer('Ali', 3),
      Answer('Aslam', 3),
      Answer('Akram', 3),
    ]),
  ];

  print(questions.length); // 3
  print(questions[0].text); // What's your favorite color?
  print(questions[0].answers); // [Answer { text: Black, score: 3 }, Answer { text: Blue, score: 1 }, Answer { text: White, score: 1 }]
  print(questions[0].answers.length); // 3
  questions[0].answers.forEach((answer) => print(answer.text)); // print all three options('text') of 'answers'
  print(questions[0].answers[0]); // Answer { text: Black, score: 3 }
  print(questions[0].answers[0].text); // Black
  print(questions[0].answers[0].score); // 3
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this trick.

var answers = questions[0]['answers'] as List<Map<String, Object>>;
print('${answers.length}'); //3
print('${answers[0]}'); //{text: Black, score: 3}

Or one line.

print('${(questions[0]['answers'] as List<Map<String, Object>>).length}'); //3

1 Comment

That's helpful indeed. Thanks @suhaib

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.