Was unable to sort a list of objects in flutter
1,988
sort method doesn't return a list, it is a void function. You should do it like this:
messageList = datasnapshot.documents
.map(
(v) => Message(
message: v.data['msg'],
sender: v.data['sender'],
imgUrl: v.data['imgUrl'],
id: v.data['id']),
)
.toList()
messageList.sort((m, m2) => int.parse(m.id).compareTo(int.parse(m2.id)));
Author by
Hardeep Singh
Updated on December 15, 2022Comments
-
Hardeep Singh over 1 year
I was working on a project where I need to sort a list that has objects in it, but it's giving an error.
The expression here has a type of 'void', and therefore can't be used.
Here my code:-
@override void initState() { super.initState(); subscription = collectionReference.snapshots().listen((datasnapshot) { setState(() { messageList = datasnapshot.documents .map( (v) => Message( message: v.data['msg'], sender: v.data['sender'], imgUrl: v.data['imgUrl'], id: v.data['id']), ) .toList().sort((m, m2) => int.parse(m.id).compareTo(int.parse(m2.id))); }); }); }
Its raising error at sort method :-
.toList().sort((m, m2) => int.parse(m.id).compareTo(int.parse(m2.id)));
What should I do to fix it, or is there any other way to sort a list of objects.
One more extra question. Documents in my firestore collection are not being added chronologically-sorted. so, I have to do that manually. do anyone knows why they are not being chronologically-sorted as default?
Thanks in advance.
-
Hardeep Singh over 4 yearsThanks for editing. I am not that good at English. I will improve it. Thanks
-
PYB over 4 yearsDocuments are not added chronologically-sorted because this is done at the query level. Indexing is already applied automatically when new documents are added, which is how the query can sort the documents quickly.
-
-
Hardeep Singh over 4 yearsyeah, that totally makes sense. Thanks for your answer. I was struggling for it from couple of hours. Really appreciated. Thanks ones again.
-
Dpedrinha about 2 yearsI can't find the difference between this answer and the code in the question. Did you edit it to match this answer?