Home > Software engineering >  Flutter & Firebase - sorting using 2 value
Flutter & Firebase - sorting using 2 value

Time:01-11


I'm working on an app similar to a shopping list.
In the code below you can see how I get the data from firebase and I'm using orderBy to sort all the data.
For example I have:

"itemName" "itemStorage" "itemNumber"
"Tomatoes" "pantry" "2"
"Potatoes" "pantry" "5"
"Salmon" "freezer" "2"
"Beer" "pantry" "5"
"Onion" "pantry" "3"
"Pizza" "freezer" "2"

So using orderBy I can sort by itemName, itemStorage or itemNumber.
My problem is that I want to show all the items sorted by itemStorage and then ordered by itemName..I want something like this:

"Beer" "pantry" "5"
"Onion" "pantry" "3"
"Potatoes" "pantry" "5"
"Tomatoes" "pantry" "2"
"Pizza" "freezer" "2"
"Salmon" "freezer" "2"

How can I sort data using 2 values?
thanks in advance
...
child: StreamBuilder<QuerySnapshot>(
 stream: fireStore.collection('items').orderBy("itemName").snapshots(),
 builder: (context, snapshot) {
  if (!snapshot.hasData) {
   return const Text('No tasks to display');
  } else {
   return ListView(
    children: snapshot.data!.docs.map((DocumentSnapshot document) {
     Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
...
...
}


CodePudding user response:

I've solved thanks to the comment of Frank van Puffelen.
I've tried this:

fireStore.collection('items').orderBy("itemStorage").orderBy("itemName").snapshots()

then, once compiled, in the debug console i've got a firebase link for creating an index so now it works without any problem.

W/Firestore(13965): (24.3.1) [Firestore]: Listen for Query(target=Query(items order by itemStorage, itemName, __name__);limitType=LIMIT_TO_FIRST) failed: Status{code=FAILED_PRECONDITION, description=The query requires an index. https://console.firebase.google.com/....RoMCghfX25hbWVfXxAB, cause=null}
  • Related