Convert List<String> to a Map<String, list> in dart flutter

761 views Asked by At

I'm trying to convert a list of string to a map<string, list> so I can display that data in GroupListView

The data I have looks like this:

    [{"surah_no":2,"verse_no":2,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":2,"verse_no":1,"surah_name":"Al-Baqarah","favorite":true},  {"surah_no":2,"verse_no":3,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":4,"verse_no":1,"surah_name":"An-Nisa'","favorite":true}, 
{"surah_no":4,"verse_no":5,"surah_name":"An-Nisa'","favorite":true},{"surah_no":12,"verse_no":1,"surah_name":"Yusuf","favorite":true}, {"surah_no":4,"verse_no":7,"surah_name":"An-Nisa'","favorite":true}]

The data I need to display in grouplistview:

{
    'Al-Baqarah': ['2','1','3'],
    'An-Nisa': ['1','5','7'],
    'Yusuf': [1]

  };

I'm getting data from sharedpreferences like this:

 SharedPreferences pref = await SharedPreferences.getInstance();
var lb = await pref.getStringList(('bookmarks_key'));
print(lb);

How can I convert this list into a map described above? I can covert the whole list into a map but can we group the map based on a specific parameter 'surah_name' with only 'verse_no's in it? Please help! Thank you

1

There are 1 answers

5
Robert Sandberg On

Using the collection package, this will produce the desired output:

  final data = [
    {"surah_no": 2, "verse_no": 2, "surah_name": "Al-Baqarah", "favorite": true},
    {"surah_no": 2, "verse_no": 1, "surah_name": "Al-Baqarah", "favorite": true},
    {"surah_no": 2, "verse_no": 3, "surah_name": "Al-Baqarah", "favorite": true},
    {"surah_no": 4, "verse_no": 1, "surah_name": "An-Nisa'", "favorite": true},
    {"surah_no": 4, "verse_no": 5, "surah_name": "An-Nisa'", "favorite": true},
    {"surah_no": 12, "verse_no": 1, "surah_name": "Yusuf", "favorite": true},
    {"surah_no": 4, "verse_no": 7, "surah_name": "An-Nisa'", "favorite": true}
  ];

  var result = data
      .groupListsBy((e) => e['surah_name']! as String)
      .map((key, value) => MapEntry(key, value.map((v) => v['verse_no']! as int).toList()));

Here as a working example: https://dartpad.dev/23715f79111e4ffc8ac3a8f26cc3d3ad

In your desired outcome, you have mixed the verse_no as both int and String. You'll need to select one of them. I chose int now because you wrote them as int in the original data.