BlueNimbus
BlueNimbus

Reputation: 21

flutter and firestore re sort listview on data update

I am having trouble refreshing a list view when firestore item changes. It works perfectly when new items are added and they show up in the list and view is updated. We are querying with orderby clause and its on a field that changes frequently. We have noticed that the list internally changes because the order has changed but because the List view has not refreshed and reordered itself. When users click on an item they end up on a wrong item.

Here is how the widget code looks:

Widget buildFuture(bool isIndian, bool isJapan){

return FutureBuilder<Stream<List<Map<String,dynamic>>>>(

future: Provider.of<CountryProvider>(context)

.getList(currentUserId, isIndian, isJapan),

builder: (ctx, snap) {

if (!snap.hasData) {

return Center(

child: CircularProgressIndicator(),

);

}

return StreamBuilder<List<Map<String,dynamic>>>(

stream: snap.data,

builder:

(ctx, AsyncSnapshot<List<Map<String,dynamic>>> snapshot) {

if (!snapshot.hasData) {

return Center(

child: CircularProgressIndicator(),

);

}



usersData = snapshot.data;



if (snapshot.data.isEmpty) {

return Center(

child: Column(

mainAxisSize: MainAxisSize.min,

children: [

Image.asset('assets/images/icon.png'),

Text(

'Aha Nothing found',

textAlign: TextAlign.center,

style: Theme.of(context)

.textTheme

.bodyText1

.copyWith(fontSize: 18),

),

],

),

);

}



return _getListView(snapshot);

},

);

},

);

}

_getListView(snapshot) {





return ListView.builder(

itemCount: snapshot.data.length,

itemBuilder: (ctx, index) {

return UserItem(

userDocument: snapshot.data[index],

);

},

);



}

Here is how we are getting from Firestore:

Stream<QuerySnapshot> snapshots= _firestore.collection(Constants.COUNTRY_COLLECTION).where('isIndian' , isEqualTo: isIndian).where('isJapan' , isEqualTo: isJapan).orderBy("lastOnline",descending: true).snapshots();
return snapshots.transform(
StreamTransformer<QuerySnapshot, List<Map<String,dynamic>>>.fromHandlers(
handleData: (querySnapshot, sink) async {

}

There are composite indexes in firestore DB.

Upvotes: 0

Views: 861

Answers (1)

BlueNimbus
BlueNimbus

Reputation: 21

If it helps anyone. I solved it by moving my listview into reorderablelistview:

_getListView(usersData) {


        return ReorderableListView(children:  List.generate(usersData.length, (int index) {
            return UserItem(
              userDocument: usersData[index],key:UniqueKey()
            );
          },
        ),
        onReorder:_doRefreshed );

  }
 _doRefreshed(int oldIndex, int newIndex){
    print("Refresh is called");
   setState(
         () {
       if (newIndex > oldIndex) {
         newIndex -= 1;
       }

       usersData.insert(newIndex, usersData.removeAt(oldIndex));
     },
   );
 }

Upvotes: 2

Related Questions