GunJack
GunJack

Reputation: 1978

Access a list item stored in key value pair inside a list of map

I am using flutter/dart and I have run into following problem.

I have a list of map like this.

var questions = [
      {
        'questionText': 'What\'s your favorite color?',
        'answer': ['Black', 'Red', 'Green', 'White']
      },
      {
        'questionText': 'What\'s your favorite animal?',
        'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
      },
      {
        'questionText': 'What\'s your favorite movie?',
        'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
      },
    ];

Now suppose I need to get the string Tiger from this list. How do I do that? Dart is seeing this as List<Map<String, Object>> questions

Upvotes: 1

Views: 545

Answers (2)

na2axl
na2axl

Reputation: 1958

Maybe a more portable way with a function:

String getAnswer(int question, int answer) {
   return (questions[question]['answer'] as List<String>)[answer];
}

// Get 'Tiger'
String a = getAnswer(1, 1);

Upvotes: 1

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27207

You can convert object in list in following way and then use index to get any value.

var p = questions[1]['answer'] as List<String>;
print(p[1]);

Upvotes: 1

Related Questions