0

I'm attempting to extract a value from list contained in a list of maps, but am getting the following error: The operator '[]' isn't defined for the type 'Object'

From the following list, I'd like to access a value such as 'Pizza':

List<Map<String,Object>> questions = [
  {
    'question': 'What is your favorite food',
    'answers': [
      'Pizza',
      'Tacos',
      'Sushi',
    ],
  },
];

When I try to print an answer within the list of answers, it doesn't work:

// Does not work
// The operator '[]' isn't defined for the type 'Object'
print(questions[0]['answers'][0]);

I'm able to save the answers list into a variable to of type list then print a specific list item:

// Works
List answerList = questions[0]['answers'];
print(answerList[0]);

Why doesn't the first way work, and how can I get this to work with one command?

1
  • 3
    questions[0]['answers'] is declared to return an Object. Object does not have an operator [] operator. In this case, since you know that the actual type is a List<String>, you can perform an explicit cast: print((questions[0]['answers'] as List<String>)[0]); Commented Aug 31, 2020 at 20:37

1 Answer 1

2

Rather than returning an Object return a dynamic as it has an operator []

List<Map<String, dynamic>> questions = [
    {
      'question': 'What is your favorite food',
      'answers': [
        'Pizza',
        'Tacos',
        'Sushi',
      ],
    },
  ];
Sign up to request clarification or add additional context in comments.

3 Comments

Nitpick, dynamic doesn't have an [] operator. It is a special type in Dart that informs the runtime to attempt any operation, conversion, or member accessor on the underlying object without performing static type checking and to throw an error if the attempt fails.
@Abion47 any better way to do it?
@Teknoville For any arbitrary JSON-like data, not really. For complex data with a strict and guaranteed structure? Make classes.

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.