您如何在Google Firestore中存储N个项目的有序列表?
例如,待办事项清单。我有一些想法,但似乎都不太明智。
您可以在项目上放置一个“位置”键,但这将需要更新所有项目的位置值,当其中一个发生更改时。
您可以将它们存储在排序数组中,并在持久化之前进行一些切割以重新排序。
我很想听听推荐的方法是什么。
您如何在Google Firestore中存储N个项目的有序列表?
例如,待办事项清单。我有一些想法,但似乎都不太明智。
您可以在项目上放置一个“位置”键,但这将需要更新所有项目的位置值,当其中一个发生更改时。
您可以将它们存储在排序数组中,并在持久化之前进行一些切割以重新排序。
我很想听听推荐的方法是什么。
我使用的方法不需要更新所有文档,而只需使用“position”属性来更新您要排序的文档(我认为这是Trello列表的工作方式)。
假设您有一个包含5个元素的列表:
- A (position: 1)
- B (position: 2)
- C (position: 3)
- D (position: 4)
- E (position: 5)
- A (position: 1)
- C (old position: 3, new?) <---- you need to calculate this new position
- B (position: 2)
- D (position: 4)
- E (position: 5)
此时,您只需要知道前一个元素的位置和下一个元素的位置:
(A + B) / 2 = 1.5
1.5 是 "C" 的新位置。
- A (position: 1)
- C (position: 1.5) <--- update only this doc in your db
- B (position: 2)
- D (position: 4)
- E (position: 5)
让我们把C再次移动到最新的位置。在这种情况下,您没有下一个元素,所以要做last + 0.5
:
- A (position: 1)
- B (position: 2)
- D (position: 4)
- E (position: 5)
- C (new position: 5.5)
next / 2
,否则将其设为0.5
。- C (new position: A / 2 = 0.5)
- A (position: 1)
- B (position: 2)
- D (position: 4)
- E (position: 5)
main() {
List myList = [
{'id': 'red', 'test': 'some data'},
{'id': 'green', 'other': 'some other data'},
{'id': 'blue'},
];
List myOrderList = ['green', 'red', 'blue'];
List orderByOtherList(List theList, String commonField, List orderList) {
List listOut = [];
orderList.forEach((o) => listOut.add(theList.firstWhere((m) => m[commonField] == o)));
return listOut;
}
print(myList);
print(orderByOtherList(myList, 'id', myOrderList));
}
您可以使用id:data分支和id:idPrevious分支来使用实时数据库。
基本上您正在创建一个链接列表,这将允许您在添加时进行两次写入,而在删除时进行一次写入。重新排序/移动将需要重写三个内容。以下是一个示例:
原始
id:data 1:A, 2:B, 3:C, 4:D, 5:E
id:idPrevious 1:0, 2:1, 3:2, 4:3, 5:4
修改后 ABCDE->ADBCE
id:data 1:A, 2:B, 3:C, 4:D, 5:E - 保持不变
id:idPrevious 1:0, 2:4, 3:2, 4:1, 5:3 - 最多更改3项
进一步的细节:
5:3 发生在从订单中删除 D 时。 4:1 发生在将 D 分配到一个项目后。 2:4 发生在 D 与另一个数据块共享 idPrevious,因此感到抱歉将其踢出,它提供其id作为被踢出的项目的idPrevious。