Sort a list of object by bool value

2,524

According this answer i got right result :

You can define you own compare function for bool and pass it to the sort method of List.

Example with booleans as your bool List:

booleans.sort((a, b) {
  if(b) {
    return 1;
  }
  return -1;
});

This example tells the sort method that true elements should be sorted higher than false elements.

Share:
2,524
Cyrus the Great
Author by

Cyrus the Great

Updated on December 23, 2022

Comments

  • Cyrus the Great
    Cyrus the Great over 1 year

    By call my service i received a list of object. this is my object schema:

    class MyCard {
      final String number;
      final String name;
      final String available;
      final bool isOwn;
    
      const MyCard({
        @required this.number,
        @required this.name,
        @required this.available,
        @required this.isOwn,
      });
    }
    

    I want to sort my list according isOwn==true.So in order to i use list.sort :

    myCards.sort((a, b) => a.isOwn - b.isOwn);
    

    This syntax is not for dart !! how can i do with flutter?

  • julemand101
    julemand101 over 3 years
    And can be simplified to: booleans.sort((a, b) => b ? 1 : -1)