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)));
Share:
1,988
Hardeep Singh
Author by

Hardeep Singh

Updated on December 15, 2022

Comments

  • Hardeep Singh
    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
      Hardeep Singh over 4 years
      Thanks for editing. I am not that good at English. I will improve it. Thanks
    • PYB
      PYB over 4 years
      Documents 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
    Hardeep Singh over 4 years
    yeah, that totally makes sense. Thanks for your answer. I was struggling for it from couple of hours. Really appreciated. Thanks ones again.
  • Dpedrinha
    Dpedrinha about 2 years
    I can't find the difference between this answer and the code in the question. Did you edit it to match this answer?