Need help. I'm sorting a list with Firestore, but when I add data, it's always created at the bottom of ListView.separated
. How to make the new data displayed not at the bottom, but at the top? As I understand it, you need to use the reverse
command, but you could indicate exactly where and how correctly.
firestore_repo
Query<Map<String, dynamic>> getMainCollection() {
FirebaseFirestore firestore = FirebaseFirestore.instance;
return firestore.collection('notes').orderBy('date');
}
list_note
child: ListView.separated(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.all(16),
separatorBuilder: (context, index) => Container(height: 5),
itemCount: widget.snapshot.data!.docs.length,
itemBuilder: (context, index) {
QueryDocumentSnapshot<Object?> documentSnapshot =
widget.snapshot.data!.docs[index];
return Dismissible(
key: Key(documentSnapshot.id),
direction: DismissDirection.endToStart,
CodePudding user response:
add this line to your ListView.separated
:
reverse: true,
so the code would be:
child: ListView.separated(
reverse: true,
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.all(16),
separatorBuilder: (context, index) => Container(height: 5),
itemCount: widget.snapshot.data!.docs.length,
itemBuilder: (context, index) {
QueryDocumentSnapshot<Object?> documentSnapshot =
widget.snapshot.data!.docs[index];
return Dismissible(
key: Key(documentSnapshot.id),
direction: DismissDirection.endToStart,
CodePudding user response:
Try this:
final reveredList = widget.snapshot.data!.docs.reversed.toList();
Then use it in the ListView
like so:
child: ListView.separated(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.all(16),
separatorBuilder: (context, index) => Container(height: 5),
itemCount: reveredList.length,
itemBuilder: (context, index) {
QueryDocumentSnapshot<Object?> documentSnapshot =
reveredList[index];
return Dismissible(
key: Key(documentSnapshot.id),
direction: DismissDirection.endToStart,
CodePudding user response:
In addition to reversing the data inside the UI/ListView
as others have shown, you can also tell Firestore to return the data in reverse order. To do this, change your orderBy
call to:
return firestore.collection('notes').orderBy('date', descending: true);