bboursaw73
bboursaw73

Reputation: 1206

Retrieve entries from map based on one of the key values

I have reviewed similar posts but am still failing to line things up with what i'm after.

I want to retrieve all entries from the following map where the condition a particular condition is met.

The simple map

List<Map<String, dynamic>> _playList = [
    {'songId': 1, 'setId': 1},
    {'songId': 2, 'setId': 1},
    {'songId': 3, 'setId': 1},
    {'songId': 4, 'setId': 2},
    {'songId': 5, 'setId': 3},
    {'songId': 6, 'setId': 4},
    {'songId': 6, 'setId': 5},
    {'songId': 6, 'setId': 6},
    {'songId': 6, 'setId': 7},
  ];

I am trying to use a method which will iterate through this map, find all entries for the int that was passed into the method and then store the results in a new array.

The method I have so far

Future<List<Song>> songFromCurrentSetlist (int setlistId) async {
    _playList.forEach((_) => setlistId == _playList.???);
  }

Clearly, a bit stuck.

Basically, if 1 is received for setlistId in the parameter list for the method, I am expecting to get back the values 1,2,3 for each of the songIds that exist for setlistId == 1.

Thank you, Bob

Upvotes: 0

Views: 75

Answers (2)

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

You can create a list of songs and add new songs when your setId match.

Following Example Clear your Idea.

void main(){ 
List<Map<String, dynamic>> _playList = [
    {'songId': 1, 'setId': 1},
    {'songId': 2, 'setId': 1},
    {'songId': 3, 'setId': 1},
    {'songId': 4, 'setId': 2},
    {'songId': 5, 'setId': 3},
    {'songId': 6, 'setId': 4},
    {'songId': 6, 'setId': 5},
    {'songId': 6, 'setId': 6},
    {'songId': 6, 'setId': 7},
  ];

  List<int> songs = [];
   songFromCurrentSetlist (int setlistId) async {
     _playList.forEach((index){
       if(index['setId'] == setlistId){
         songs.add(index['songId']);
       }
    });
  }

  songFromCurrentSetlist(1);

  print(songs.toList());
}

Upvotes: 1

Deepak
Deepak

Reputation: 157

Instead of Map why you not using model class Exp:

class Songs{
final int songId;
final int setId;
Songs(this.songId, this.setId);}
ListSongs> _playList

try using this

Upvotes: 0

Related Questions