我正在尝试将字符串列表转换为映射<字符串,列表>这样我就可以在GroupListView 中显示该数据
我的数据看起来是这样的:
[{"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}]
我需要在grouplistview中显示的数据:
{
'Al-Baqarah': ['2','1','3'],
'An-Nisa': ['1','5','7'],
'Yusuf': [1]
};
我从共享引用中获取数据,如下所示:
SharedPreferences pref = await SharedPreferences.getInstance();
var lb = await pref.getStringList(('bookmarks_key'));
print(lb);
如何将此列表转换为上述地图?我可以将整个列表转换为一个映射,但我们可以根据一个特定的参数"surah_name"将映射分组,其中只有"verse_no"吗?请帮忙!谢谢
使用收集包,这将产生所需的输出:
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()));
以下是一个工作示例:https://dartpad.dev/23715f79111e4ffc8ac3a8f26cc3d3ad
在您想要的结果中,您将verse_no混合为int
和String
。您需要从中选择一个。我现在选择int
是因为您在原始数据中将它们写为int
。