Flutter making a directory index [closed]

对着背影说爱祢 提交于 2021-01-29 13:55:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!