问题
Im facing challenge creating a directory with alphabet index.
I have List<Map<String, dynamic>> of shops like below:
var shops = [
{'name':'Thrifty','products':'cars', 'delivery':'no'},
{'name':'Pizza Express','products':'pizza', 'delivery':'yes'},
{'name':'Fastmart','products':'household items', 'delivery':'yes'}
];
and would like to render list of cards separated with alphabet like below:
I'm using cloud firestore to get my data, if there is a way to query the database directly or have it done client-side please let me know.
Appreciate any help and guidance !
回答1:
I could give you an idea. Try something like this,
var shops = [
{'name':'Thrifty','products':'cars', 'delivery':'no'},
{'name':'Pizza Express','products':'pizza', 'delivery':'yes'},
{'name':'Fastmart','products':'household items', 'delivery':'yes'}
];
var indexedShops = {};
shops.forEach((item) {
String letter = item['name'][0];
if(indexedShops[letter] != null){
indexedShops[letter] += [item];
}else{
indexedShops[letter] = [item];
}
});
print(indexedShops);
// {T: [{name: Thrifty, products: cars, delivery: no}], P: [{name: Pizza Express, products: pizza, delivery: yes}], F: [{name: Fastmart, products: household items, delivery: yes}]}
var availLetters = indexedShops.keys.toList();
availLetters.sort();
availLetters.forEach((e){
print(indexedShops[e]);
});
// [{name: Fastmart, products: household items, delivery: yes}]
// [{name: Pizza Express, products: pizza, delivery: yes}]
// [{name: Thrifty, products: cars, delivery: no}]
First of all, we declare a Map
to store the objects letter-wise.
Then, make a list of available letters and sort them for display purposes.
Then, iterate through it for different use cases.
Hope that suits your case!
来源:https://stackoverflow.com/questions/64596751/flutter-making-a-directory-index