Sort list flutter

2,931

Solution 1

You just need to perform custom sorting here, rest of the things will remain same.

  List list = [{"fid":1,"name":"z"},{"fid":10,"name":"b"},{"fid":5,"name":"c"},{"fid":4,"name":"d"}];
  
  list.sort((a,b)=> a["fid"].compareTo(b["fid"]));
  
  int fidIndex=4;
  
  int indexToRemove=list.indexWhere((element) => element["fid"]==fidIndex);

  Map<String,dynamic> removedItem= list.removeAt(indexToRemove);

  list.insert(0,removedItem); 

  print(list);

Solution 2

You can sort list using comparator:

const list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
const fixedFid = 3

const sortedList = list.sort( (item1, item2) => { 
    if (item1.fid === fixedFid){
        return -1
    }
    if (item2.fid == fixedFid){
        return 1
    }
    return item1.fid.localeCompare(item2.fid)
})
Share:
2,931
John Joe
Author by

John Joe

Keep Coding ~

Updated on December 24, 2022

Comments

  • John Joe
    John Joe over 1 year

    I'm looking for a simplest way to sort list based on given value instead of using two list.

    Example I have list [a,b,c,d], with a given value d,I can sort it like this:

    enter image description here

    But if I have an object list, how can I sort it based on given value?

    Example

    List<ABC> list = [{fid:1,name:"a"},{fid:2,name:"b"},{fid:3,name:"c"},{fid:4,name:"d"}]
    

    I have value 3. I want to sort the list become

    List<ABC> list = [{fid:3,name:"c"},{fid:1,name:"A"},{fid:2,name:"b"},{fid:4,name:"d"},{fid:4,name:"d"}]
    
    • pskink
      pskink over 3 years
      so what sort order do you want to have? the two lists you posted are completly different lists
    • John Joe
      John Joe over 3 years
      @pskink I want to sort it based on a given fid.
    • pskink
      pskink over 3 years
      you already got an answer: list.sort((a,b)=> a["fid"].compareTo(b["fid"]));
  • John Joe
    John Joe over 3 years
    But what if I only given a fid?
  • John Joe
    John Joe over 3 years
    But what if I only given a fid?
  • Alexander Karp
    Alexander Karp over 3 years
    @JohnJoe You can create custom comparator and define rules according your fields, so instead of using name property you can use fid, I updated the code