Home > Back-end >  Dart: Convert map (Key / Value) into an Ordered List[]
Dart: Convert map (Key / Value) into an Ordered List[]

Time:08-24

I'm receiving a document snapshot from firestore and I convert it into a Map<String, dynamic> and I know that maps are not ordered, however, I want to order the layout of my screen fields in a certain order. Problem is, the order that I want to achieve is not alphabetical. Here is a sample of my map:

Map<String, dynamic> customerInfo = {
  'إسم العميل': 'John Doe',  // CustomerName
  'العنوان': 'Pennsylvania Ave.', // Address
  'اللون المفضل': 'Blue',  // Favorite Color
}

So, I am sending this map to a loop to iterate over keys/values and converting them into a list of widgets, however, for some screens I need to have 'CustomerName' be the first widget, and 'Address' be the second widget, and vice versa for other screens. Some maps will have more fields, those extra fields will not matter later on, I just want to maintain a certain order for certain fields if they exist.

I tried looping over the keys using a switch / if to match the keys and do a List<Widget>().add(Text(key, value)) however, the generated list is still unordered obviously.

Can I use a List<String> arranged as my preferred order and convert the map based on this list?

Any other options to achieve this please?

Thanks

CodePudding user response:

Maybe you can use a LinkedHashMap. It keeps the key insertion order.

CodePudding user response:

FirebaseFirestore has a .orderBy() function that you can use to order your data when you query a collection.

    QuerySnapshot<Map<String, dynamic>> snapshot = 
await firestoreInstance.collection('collectionName')
         .orderBy('value', descending: false)
        .get();

Note: Your question seems like you're trying to get a list of Customer Info from firebase, so all you have to do is replace the 'collectionName' in my code with the name of the customer info collection. This is a querysnapshot because it queries the collection and gets you all the customer info in the collection.

You will also have to replace the 'Value' in my code here with the key of the value you want it to be ordered with. You can also choose whether it should be ascending or descending by setting the descending value to either true or false.

I hope this helps.

  • Related