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)
})
Comments
-
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 valued
,I can sort it like this: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 over 3 yearsso what sort order do you want to have? the two lists you posted are completly different lists
-
John Joe over 3 years@pskink I want to sort it based on a given fid.
-
pskink over 3 yearsyou already got an answer:
list.sort((a,b)=> a["fid"].compareTo(b["fid"]));
-
-
John Joe over 3 yearsBut what if I only given a fid?
-
John Joe over 3 yearsBut what if I only given a fid?
-
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