Home > Mobile >  How to print from nested map in Dart
How to print from nested map in Dart

Time:03-28

I want to print score value only

    void main() {
           List questions =  [
            {
              'questionText': 'What\'s your favorite color?',
              'answers': [
                {'text': 'Black', 'score': 10},
                {'text': 'Red', 'score': 0},
                {'text': 'Green', 'score': 0},
                {'text': 'White', 'score': 0},
              ],
            },
          ];

I tried to do

print(questions[0]["score"])

But it doesn't work. can anyone help me please

CodePudding user response:

When you access questions[0] you are getting the first element in the array, which in this case is:

{
  'questionText': 'What\'s your favorite color?',
  'answers': [
    {'text': 'Black', 'score': 10},
    {'text': 'Red', 'score': 0},
    {'text': 'Green', 'score': 0},
    {'text': 'White', 'score': 0},
  ],
}

When you then write questions[0]["score"] you are trying to get the key score, which as you can see is null.

You should instead access answers inside the object, take a look at the examples below:

print(questions[0]["score"]); // null
print(questions[0]['answers'][0]['score']); // 10
print(questions[0]['answers'].map((answer) => answer['score'])); // (10, 0, 0, 0)
  •  Tags:  
  • dart
  • Related