Flutter/Dart: How to get list value where key equals

Viewed 19352

I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".

//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];

//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);

Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?

EDIT: Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:

for (int i = 0; i < userDocument.length; i++) {
  var trendColorMap = {
     'name': userDocument[i]['name'],
     'color': userDocument[i]['color'].toString(),
  };
  trendsList.add(trendColorMap);
}
1 Answers

I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.

A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.

String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];

//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);

Check that out, and let me know if that helps you, I am sure it will :)

Related