How could I implement Firestore so that users can sort items in an array and the sort order is synced? For example order items in a Todo list.
I can come up with 2 alternatives. But they don't feel like good ideas..
Insert an item at a specified index. But I'm not sure how to or if you can do that with Firestore?
Every time you add a new item or "move" an item map new sortKey-values to each item then update all items. I might be able to so this with .batch but it feels super inefficient?
There must be a better way!
What I'd recommend is to have a
position
field in your document that you will set to a floating point value. Listen to the collection with the query ordered by position. Then:lastItem.position + 100
position
to(prev.position + next.position) / 2.0
firstItem.position / 2.0
This way you can continuously reorder items without having to do batched writes. Let's take a look at an example: