firebasefluttergoogle-cloud-firestorereorderable-list

Firebase Collection into ReorderableListView


I have a Firebase collection in Flutter that I want to have in a reorderableListView. The documents in the collection have a 'position' field that should determine the order of the list and be updated onReorder of the list.


Solution

  • I've worked it out myself finally.

    onReorder: (oldIndex, newIndex) {
      setState(() {
        List<MyObjectClass> objectList =
            myObjects
                .data;
        if (newIndex > oldIndex) {
          newIndex -= 1;
        }
    
        final MyObjectClass
            myObject = objectList.removeAt(oldIndex);
        objectList.insert(newIndex, myObject);
    
        for (MyObjectClass o in objectList) {
          o.position = objectList.indexOf(o);
          DatabaseService()
              .updateMyObjects(
                  o);
        }
      });
    }
    

    This is assuming you've got a function in a DatabaseService() class that maps a Firestore Collection to objects, and then have the ReorderableListView in a StreamBuilder that passes it a snapshot of said objects 'myObjects'.