'Flutter: The getter 'answers' isn't defined for the class 'List<Map<String, Object>>'
I am trying to access 'second' from the below:
final basic_answers = const [
{
'questionText': 'Q1. Who created Flutter?',
'answers': [
{'first': 'Facebook', 'score': -2},
{'second': 'Adobe', 'score': -2},
{'third': 'Google', 'score': 10},
{'fourth': 'Microsoft', 'score': -2},
],
},
];
using this:
print(basic_answers.answers.second);
However it gives the below error:
Flutter: The getter 'answers' isn't defined for the class 'List<Map<String, Object>>'.
What would the solution be for this? Thanks!
Solution 1:[1]
You probably should familiarize yourself again with Map and List in Dart (https://api.dart.dev/stable/2.17.0/dart-core/Map-class.html and https://api.dart.dev/stable/2.17.0/dart-core/List-class.html).
basic_answers is a List containing Map<String, Object> elements, so doing basic_answers.answers will not work, since List does not have a getter for answers. Even basic_answers[0].answers will not work,. since the elements are of type Map<String, Object>.
To access values inside a Map you can use the [] operator (https://api.dart.dev/stable/2.17.0/dart-core/Map/operator_get.html), so for example basic_answers[0]['answers'] to access the List of answers. The elements in this List again are of type Map<String, Object> so directly accessing second will not work either. One options would be to do something like:
print((basic_answers[0]['answers'] as List).firstWhere((el) => el.containsKey('second')));
This gets the first element of the List, and then gets the value for the key answers from this Map. Since the value is another List we now can use firstWhere (https://api.dart.dev/stable/2.17.0/dart-core/Iterable/firstWhere.html) to find the first element (Map) which contains the key 'second'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | puelo |
