For example, in Firestore I have JSON like this
// Document 1
{
"type":"Child",
"createdDate":"01/01/2020",
"birthDate":"08/01/2002",
}
// Document 2
{
"type":"Adult",
"createdDate":"05/01/2020",
"birthDate":"08/01/1990",
}
I want to turn this function in to firebase query
(a, b) {
DateTime da = a["type"] == "Child" ? a["createdDate"]: a["birthDate"];
DateTime db = a["type"] == "Child" ? a["createdDate"]: a["birthDate"];
return da.compareTo(db);
}
// In short if it a Child, select `createdDate` to compare, else select `birthDate` to compare.
Can I do this in firebase?
I can’t query all data then sort in frontend because I want to use FirestoreListView
2
Answers
The only way I see, is to create a helper field in the DB which shows the createdDate for children and the birthDate for adults. Then you can sort for this field
I have not your Class model so I run the logic on the list but you can do this on model too.
First you can’t sort a list with two different sort, I recommend first split those into two group as
child
andadult
, then sort theme then merge them together, for grouping I used collection package, let say this is your list:you can sort them like this:
result: