Let's say we have a class called Thing
, which is defined as follows:
class Thing {
final int id;
final String name;
Thing(this.id, this.name);
}
and we have a list of this class that is like this:
final List<Thing> things= [
Thing(1, 'Black Car'),
Thing(2, 'Red Car'),
Thing(3, 'Car'),
Thing(4, 'Green Car'),
Thing(5, 'Car Yellow'),
Thing(6, 'Car Blue'),
];
now we want to search in this list for some things using the word Car
like this:
things.where(
(thing) => thing.name.contains('Car')
).toList()
the result will be:
[
Thing(1, 'Black Car'),
Thing(2, 'Red Car'),
Thing(3, 'Car'),
Thing(4, 'Green Car'),
Thing(5, 'Car Yellow'),
Thing(6, 'Car Blue'),
]
now how can I sort this result by the things which names start with the search word Car
, in other words, I want this to be the result:
[
Thing(3, 'Car'),
Thing(5, 'Car Yellow'),
Thing(6, 'Car Blue'),
Thing(2, 'Red Car'),
Thing(1, 'Black Car'),
Thing(4, 'Green Car'),
]
thanks in advance.
CodePudding user response:
With List.sort, you give a priority when things start with "Car":
final filteredThings = things.where(
(thing) => thing.name.contains('Car')
).toList();
filteredThings.sort((a, b) {
if (a.startsWith('Car') && !b.startsWith('Car')) {
return 1;
}
if (b.startsWith('Car') && !a.startsWith('Car')) {
return -1;
}
return a.name.compareTo(b.name);
});
CodePudding user response:
You can use sort function to sort the list as you want. Here is a working sample:
class Thing {
final int id;
final String name;
Thing(this.id, this.name);
Map toJson() {
Map data = {};
data['id'] = id;
data['name'] = name;
return data;
}
}
final List<Thing> things = [
Thing(1, 'Black Car'),
Thing(2, 'Red Car'),
Thing(3, 'Car'),
Thing(4, 'Green Car'),
Thing(5, 'Car Yellow'),
Thing(6, 'Car Blue'),
];
void main() async {
List<Thing> myList =
things.where((thing) => thing.name.contains('Car')).toList();
myList
..sort((Thing a, Thing b) {
int indexOfCarInA = a.name.indexOf('Car');
int indexOfCarInB = b.name.indexOf('Car');
if (indexOfCarInA < indexOfCarInB)
return -1;
else if (indexOfCarInA == indexOfCarInB) if (a.id <= b.id) return -1;
return 1;
});
myList.forEach((element) {
print(element.toJson());
});
}