Sourish Mukherjee
Sourish Mukherjee

Reputation: 179

Flutter - ReOrder Data Stored in FireStore

enter image description here

As you can see, I am dragging Tasks by using ReorderableListView widget of Flutter.

The onReorder is able to drag the tasks up and down. However, when I close the app, all of the tasks go in the default order as it was arranged.

This is because my data which is being fetched from the CloudFireStore isn't changing its order, the way is it updated in my dragging.

Can anyone help me, how can I update the position of tasks stored as documents in Cloud FireStore, so that when I close the app and open it again, it shows new updated positions and not old positions of the task

enter image description here

The code :

child: StreamBuilder(
                    stream: FirebaseFirestore.instance
                        .collection("Tasks")
                        .doc(_email)
                        .collection("User_Tasks_List")
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return const Text("Loading!...");
                      _docs = snapshot.data.documents;
                      return Theme(
                        data: ThemeData(canvasColor: Colors.transparent),
                        child: ReorderableListView(
                            children: _docs
                                .map((e) => InkWell(
                                    key: ObjectKey(e),
                                    onTap: () => _popupDialog(context, e),
                                    onDoubleTap: () => FirebaseFirestore
                                            .instance
                                            .runTransaction(
                                                (transaction) async {
                                          transaction.delete(e.reference);
                                          Fluttertoast.showToast(
                                              msg: "Task has been deleted!");
                                        }),
                                    child: ViewHolder(e)))
                                .toList(),
                            onReorder: onReorder),
                      );
                    }),

Upvotes: 1

Views: 802

Answers (1)

trizin
trizin

Reputation: 343

You can add a parameter like index:x to items in firestore. Then you need to save the order of the ordered list items and store them in Firestore using the indexes.

When you fetch items you need to sort them by this index and you will get the same order.

objects.sort((a, b) => a.index.compareTo(b.index));

Upvotes: 1

Related Questions