How to remove a specific object from a list in dart/flutter? - list

I have a list called selected list of type dynamic and it holds a list of objects, each objects contains from a teacher ID & index.
I want to check if this list contains the same Id & index, if it does i want to remove this object from the list.
here is my code ....
void addTeacher(int teacherId, int index) {
if (this.selectedList.contains({ **/// the problem is here** })) {
this.selectedList.remove({teacherId, index});
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
this.selectedList.add({teacherId, index});
this.myColor = AsasColors().blue;
print('added teacher => ${teacherId.toString()}');
}
notifyListeners();
print(selectedList);
}
how can i achive this ?

Contains and remove use the == operator which in this case will return false because unless you override it for a specific class it will compare by reference.
You can use indexWhere to find out if an item is in a list based on a compare function like that (if the function returns -1 the item is not on the list:
// Index different than -1 means the item is found somewhere in the list
final teacherIndex = this.selectedList.indexWhere((teacher) => teacher['teacherId'] == teacherId);
if (teacherIndex != -1) {
this.selectedList.removeAt(teacherIndex);
this.myColor = Colors.grey;
print('removed teacher => ${teacherId.toString()}');
} else {
...
}

I have implemented it and it worked fine
[The code]
[The output:]
This is the written code:
class Subject {
int? teacherID;
int? subjectID;
Subject(this.teacherID, this.subjectID);
#override
String toString() => "Subject {teacherID: $teacherID, subjectID: $subjectID";
//TODO: Change your needed criteria here..
#override
bool operator ==(Object other) =>
other is Subject &&
teacherID == other.teacherID &&
subjectID == other.subjectID;
}
void addSubject(List<Subject> list, Subject subject) {
if (list.contains(subject)) {
list.remove(subject);
} else {
list.add(subject);
}
}
void main() {
List<Subject> selectedList =
List.generate(10, (index) => Subject(index + 1, index + 1));
print("SelectedList = $selectedList");
addSubject(selectedList, Subject(11, 11));
addSubject(selectedList, Subject(11, 12));
addSubject(selectedList, Subject(12, 11));
addSubject(selectedList, Subject(12, 12));
print("SelectedList2 = $selectedList");
addSubject(selectedList, Subject(12, 12));
print("SelectedList3 = $selectedList");
}
Sincerely, accept the answer if it worked for you.

Related

Flutter Dart List - How to check if a list contains an object

I wrote a function which returns true if an element is present in a list. I created an earlier version in which the list contained "ints" and it worked fine. Now I have a list of "complex" objects, and it seems it never detects if the object is present.
Here is the code :
bool addNewWordToBufferCarnetList(int? wordId) {
CarnetWords newWord =
CarnetWords(iD: wordId!, wrong: 0, right: 0, mastery: 0);
if (_bufferCarnetList.contains(newWord) == true) {
return false;
} else {
_bufferCarnetList.add(newWord);
notifyListeners();
return true;
}
}
Is there another way to see if the list contains the object ?
As suggested and explained by pskink, I had to override the == operator in my CarnetWords class for the "equality" to function.
Here is the code :
class CarnetWords {
#override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (runtimeType != other.runtimeType) return false;
return other is CarnetWords && other.iD == iD;
}
#override
int get hashCode => iD.hashCode;
int? iD;
int? wrong;
int? right;
double? mastery;
CarnetWords(
{#required this.iD,
#required this.wrong,
#required this.right,
#required this.mastery});
}
Thanks pskink for your help and patience !

How to update length of list in dart with default value?

In my app, at many places I have used Lists like this:-
List<int> nums = [];
// initializing list dynamically with some values.
nums.length = 12; // increasing length of list
// setting these values afterward using nums[i] at different places.
Now after migrating to null-safety obviously nums.length = 4 is giving me a runtime error, so I was wondering is there any method to set the length of the list with default values such that, after if the length of the list was smaller than before then with new length extra elements are added with some default value.
Note: Of course I know we can use for loop, but I was just wondering if there is any easier and cleaner method than that.
var num = List<int>.generate(4, (i) => i);
You can read this.
Another approach:
extension ExtendList<T> on List<T> {
void extend(int newLength, T defaultValue) {
assert(newLength >= 0);
final lengthDifference = newLength - this.length;
if (lengthDifference <= 0) {
return;
}
this.addAll(List.filled(lengthDifference, defaultValue));
}
}
void main() {
var list = <int>[];
list.extend(4, 0);
print(list); // [0, 0, 0, 0];
}
Or, if you must set .length instead of calling a separate method, you could combine it with a variation of julemand101's answer to fill with a specified default value instead of with null:
class ExtendableList<T> with ListMixin<T> {
ExtendableList(this.defaultValue);
final T defaultValue;
final List<T> _list = [];
#override
int get length => _list.length;
#override
T operator [](int index) => _list[index];
#override
void operator []=(int index, T value) {
if (index >= length) {
_list.extend(index + 1, defaultValue);
}
_list[index] = value;
}
#override
set length(int newLength) {
if (newLength > length) {
_list.extend(newLength, defaultValue);
} else {
_list.length = newLength;
}
}
}
(I also made its operator []= automatically grow the ExtendableList if the specified index is out-of-bounds, similar to JavaScript.)
Your problem is that the List in Dart does not have the concept of adding more space while you promise that you are not going to use this new capacity before it is set.
But you can easily make your own List implementation which does this:
import 'dart:collection';
void main() {
List<int> nums = ExtendableList();
nums.length = 3;
nums[2] = 1;
nums[0] = 1;
nums[1] = 1;
print(nums); // [1, 1, 1]
nums.add(2);
print(nums); // [1, 1, 1, 2]
print(nums.runtimeType); // ExtendableList<int>
}
class ExtendableList<T> with ListMixin<T> {
final List<T?> _list = [];
#override
int get length => _list.length;
#override
T operator [](int index) => _list[index] as T;
#override
void operator []=(int index, T value) => _list[index] = value;
#override
set length(int newLength) => _list.length = newLength;
}
As you can see we are using a null type behind the scene but from the outside it will work like the list contains non-nullable. This only works because we assume the [] operator will not be called while a null value are in the list (which happens if we extend the list and does not set the value).
I should add that using such a List implementation does comes with great risk since you don't get any warning/error from the analyzer if you are using it wrongly.
You have to use a list of nullable element to make it longer.
List<int?> nums = [];
nums.length = 4; // OK
print(nums); // [null, null, null, null]
You can also use filled method. Here growable is false by default.
void main() {
var a = List<int>.filled(3, 0, growable: true);
print(a);
// [0, 0, 0]
}
Refer: https://api.flutter.dev/flutter/dart-core/List/List.filled.html

How to update a variable maintaining the length of a list in a cascade-like structure?

class CoinData {
var _controller = StreamController<Map<String,dynamic>>();
.....
Stream<Map<String,dynamic>> getAllCurrentRates() {
int numAssets = 0;
int counter = 0;
this.listAllAssets()
.then((list) {
if (list != null) {
numAssets = list.length;
List<Map<String, dynamic>>.from(list)
.where((map) => map["type_is_crypto"] == 1)
.take(3)
.map((e) => e["asset_id"].toString())
.forEach((bitCoin) {
this.getCurrentRate(bitCoin)
.then((rate) => _controller.sink.add(Map<String,dynamic>.from(rate)))
.whenComplete(() {
if (++counter >= numAssets) _controller.close();
});
});
}
});
return _controller.stream;
}
.....
}
The length of returned list is around 2500 and this value is assumed by numAssets, however as you see that list is modified later and therefore its length is less, then the evaluation (++counter >= numAssets) is incorrect. So, is it possible to fix that code maintaining its current structure?
.take(3) is temporal, it shall be removed later.

Flutter: How to sort a list by two or more fields? [duplicate]

How to sort a list of objects by the alphabetical order of one of its properties (Not the name but the actual value the property holds)?
You can pass a comparison function to List.sort.
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
In general, you can provide a custom comparison function to List.sort.
/// Desired relation | Result
/// -------------------------------------------
/// a < b | Returns a negative value.
/// a == b | Returns 0.
/// a > b | Returns a positive value.
///
int mySortComparison(SomeClass a, SomeClass b) {
final propertyA = someProperty(a);
final propertyB = someProperty(b);
if (propertyA < propertyB) {
return -1;
} else if (propertyA > propertyB) {
return 1;
} else {
return 0;
}
}
list.sort(mySortComparison);
If you're sorting some custom class you own, you alternatively could make your class implement the Comparable interface:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) {
if (someProperty < other.someProperty) {
return -1;
} else if (someProperty > other.someProperty) {
return 1;
} else {
return 0;
}
}
}
and then you can use list.sort() directly without supplying a callback.
Note that if you're sorting by a single property that already implements the Comparable interface, implementing the comparison functions is much simpler. For example:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) =>
someProperty.compareTo(other.someProperty);
}
Reversing
If you want to reverse the sort order, you can:
Make your comparison function return a value with the opposite sign.
Alternatively just explicitly reverse the list after sorting:
list = (list..sort()).reversed.toList();
Sorting by multiple properties (a.k.a. subsorting)
There are a variety of ways to sort by multiple properties.
A general way is to perform a stable sort for each property in reverse order of importance. For example, if you want to sort names primarily by surname and then subsort within surnames by given name, then you would first sort by given names, and then perform a stable sort by surname. See below for how to perform a stable sort.
Alternatively, you could sort with a comparison function that itself checks multiple properties. For example:
class Name {
Name({String? surname, String? givenName})
: surname = surname ?? "",
givenName = givenName ?? "";
final String surname;
final String givenName;
}
int compareNames(Name name1, Name name2) {
var comparisonResult = name1.surname.compareTo(name2.surname);
if (comparisonResult != 0) {
return comparisonResult;
}
// Surnames are the same, so subsort by given name.
return name1.givenName.compareTo(name2.givenName);
}
package:collection provides an extension to chain comparison functions so that combining them is a bit more straightforward and less error-prone:
import 'package:collection/collection.dart';
int compareSurnames(Name name1, Name name2) =>
name1.surname.compareTo(name2.surname);
int compareGivenNames(Name name1, Name name2) =>
name1.givenName.compareTo(name2.givenName);
final compareNames = compareSurnames.then(compareGivenNames);
My dartbag package also provides a compareIterables function that allows comparing Lists of property values in order of importance:
import 'package:dartbag/collection.dart';
int compareNames(Name name1, Name name2) =>
compareIterables(
[name1.surname, name1.givenName],
[name2.surname, name2.givenName],
);
Okay, I want a stable sort
List.sort is not guaranteed to be a stable sort. If you need a stable sort, package:collection provides insertionSort and mergeSort implementations that are stable.
But comparing might be expensive
Suppose you have a custom comparison function that looks something like:
int compareMyCustomClass(MyCustomClass a, MyCustomClass b) {
var a0 = computeValue(a);
var b0 = computeValue(b);
return a0.compareTo(b0);
}
The sorting process might call computeValue multiple times for the same object, which is particularly wasteful if computeValue() is expensive. In such cases, a Schwartzian transform could be faster (at the expense of using more memory). This approach maps your objects to directly sortable keys, sorts those keys, and extracts the original objects. (This is how Python's sort and sorted functions work.)
Here's one possible implementation:
class _SortableKeyPair<T, K extends Comparable<Object>>
implements Comparable<_SortableKeyPair<T, K>> {
_SortableKeyPair(this.original, this.key);
final T original;
final K key;
#override
int compareTo(_SortableKeyPair<T, K> other) => key.compareTo(other.key);
}
/// Returns a sorted *copy* of [items] according to the computed sort key.
List<E> sortedWithKey<E, K extends Comparable<Object>>(
Iterable<E> items,
K Function(E) toKey,
) {
final keyPairs = [
for (var element in items) _SortableKeyPair(element, toKey(element)),
]..sort();
return [
for (var keyPair in keyPairs) keyPair.original,
];
}
void main() {
final list = <MyCustomClass>[ ... ];
final sorted = sortedWithKeys(list, computeValue);
}
My dartbag package provides such a sortWithKey function (and also a sortWithAsyncKey function if the key needs to be generated asynchronously).
If you want to sort the object "objects" by the property "name" do something like this
objects.sort((a, b) {
return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
});
Immutable extension sortedBy for List.
extension MyIterable<E> on Iterable<E> {
Iterable<E> sortedBy(Comparable key(E e)) =>
toList()..sort((a, b) => key(a).compareTo(key(b)));
}
And use
list.sortedBy((it) => it.name);
Here is my contribution to this good question. If someone is facing difficulty to understand how the #Nate Bosch answer is working & you want to sort your custom model class list then you can do this way.
1. You have to implement Comparable abstract class in your model class.
It has the method compareTo which you have to override.
For example, I have this StudentMarks model class which has marks property in it.
class StudentMarks implements Comparable {
int marks;
StudentMarks({
this.marks,
});
#override
int compareTo(other) {
if (this.marks == null || other == null) {
return null;
}
if (this.marks < other.marks) {
return 1;
}
if (this.marks > other.marks) {
return -1;
}
if (this.marks == other.marks) {
return 0;
}
return null;
}
}
2. Now you can call compareTo method inside the sort method.
void _sortStudents({bool reversed: false}) {
_students.sort((a, b) {
return a.compareTo(b);
});
if (reversed) {
_students = _students.reversed.toList();
}
setState(() {});
}
Refer to this link you want to know more about the Comparable class
https://api.dart.dev/stable/2.1.0/dart-core/Comparable-class.html
Its worked for me:
myList..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
Using Comparatorfunction, sort Users by id.
Comparator<UserModel> sortById = (a, b) => a.id.compareTo(b.id);
users.sort(sortById);
Now we can sort it in reversed/descending order.
users = users.reversed.toList();
To sort it in reverse order :
list.sort((a, b) {
return b.status.toLowerCase().compareTo(a.status.toLowerCase());
});
What's more, you can use Comparable.compare for more clear, for example:
class _Person {
final int age;
final String name;
_Person({required this.age, required this.name});
}
void _test() {
final array = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
];
// ascend with age
// Dean Jack Ben
array.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
// decend with age
// Ben Jack Dean
array.sort((p1, p2) {
return Comparable.compare(p2.age, p1.age);
});
// ascend with name
// Ben Dean Jack
array.sort((p1, p2) {
return Comparable.compare(p1.name, p2.name);
});
}
Similar to #pavel-shorokhovs answer, but strongly typed:
extension IterableExtensions<T> on Iterable<T> {
Iterable<T> sortBy<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
toList()..sort((a, b) => selector(a).compareTo(selector(b)));
Iterable<T> sortByDescending<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
sortBy(selector).toList().reversed;
}
i had fpgrowth machine learning output/result with each element of list contains another list and frequency field i was to sort by frequency in descending order so i used a bit of recursion for that try it might work i know i am late but i am posting maybe someone else could benefit.
sort(List<FrequentItem> fqItems) {
int len = fqItems.length;
if(len==2){
if(fqItems[0].frequency>fqItems[1].frequency){
sortedItems.add(fqItems[0]);
sortedItems.add(fqItems[1]);
}else{
sortedItems.add(fqItems[1]);
sortedItems.add(fqItems[0]);
}
return;
}else{
FrequentItem max = fqItems[0];
int index =0;
for(int i=0;i<len-2;i++){
if(max.frequency<fqItems[i+1].frequency){
max = fqItems[i+1];
index = i+1;
}
}
sortedItems.add(max);
fqItems.removeAt(index);
sort(fqItems);
}
}
Step 1: Add compareTo method to class:
class Student {
String? name;
int? age;
Student({this.name, this.age});
int getAge() {
if (age == null) return 0;
return age!;
}
#override
int compareTo(Student other) {
var a = getAge();
var b = other.getAge();
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
}
Step 2: Sorting your list:
By ascending:
studentList.sort((a, b) {
return a.compareTo(b);
});
By descending:
studentList.sort((a, b) {
return b.compareTo(a);
});

Sort a list of objects in Flutter (Dart) by property value

How to sort a list of objects by the alphabetical order of one of its properties (Not the name but the actual value the property holds)?
You can pass a comparison function to List.sort.
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
In general, you can provide a custom comparison function to List.sort.
/// Desired relation | Result
/// -------------------------------------------
/// a < b | Returns a negative value.
/// a == b | Returns 0.
/// a > b | Returns a positive value.
///
int mySortComparison(SomeClass a, SomeClass b) {
final propertyA = someProperty(a);
final propertyB = someProperty(b);
if (propertyA < propertyB) {
return -1;
} else if (propertyA > propertyB) {
return 1;
} else {
return 0;
}
}
list.sort(mySortComparison);
If you're sorting some custom class you own, you alternatively could make your class implement the Comparable interface:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) {
if (someProperty < other.someProperty) {
return -1;
} else if (someProperty > other.someProperty) {
return 1;
} else {
return 0;
}
}
}
and then you can use list.sort() directly without supplying a callback.
Note that if you're sorting by a single property that already implements the Comparable interface, implementing the comparison functions is much simpler. For example:
class MyCustomClass implements Comparable<MyCustomClass> {
...
#override
int compareTo(MyCustomClass other) =>
someProperty.compareTo(other.someProperty);
}
Reversing
If you want to reverse the sort order, you can:
Make your comparison function return a value with the opposite sign.
Alternatively just explicitly reverse the list after sorting:
list = (list..sort()).reversed.toList();
Sorting by multiple properties (a.k.a. subsorting)
There are a variety of ways to sort by multiple properties.
A general way is to perform a stable sort for each property in reverse order of importance. For example, if you want to sort names primarily by surname and then subsort within surnames by given name, then you would first sort by given names, and then perform a stable sort by surname. See below for how to perform a stable sort.
Alternatively, you could sort with a comparison function that itself checks multiple properties. For example:
class Name {
Name({String? surname, String? givenName})
: surname = surname ?? "",
givenName = givenName ?? "";
final String surname;
final String givenName;
}
int compareNames(Name name1, Name name2) {
var comparisonResult = name1.surname.compareTo(name2.surname);
if (comparisonResult != 0) {
return comparisonResult;
}
// Surnames are the same, so subsort by given name.
return name1.givenName.compareTo(name2.givenName);
}
package:collection provides an extension to chain comparison functions so that combining them is a bit more straightforward and less error-prone:
import 'package:collection/collection.dart';
int compareSurnames(Name name1, Name name2) =>
name1.surname.compareTo(name2.surname);
int compareGivenNames(Name name1, Name name2) =>
name1.givenName.compareTo(name2.givenName);
final compareNames = compareSurnames.then(compareGivenNames);
My dartbag package also provides a compareIterables function that allows comparing Lists of property values in order of importance:
import 'package:dartbag/collection.dart';
int compareNames(Name name1, Name name2) =>
compareIterables(
[name1.surname, name1.givenName],
[name2.surname, name2.givenName],
);
Okay, I want a stable sort
List.sort is not guaranteed to be a stable sort. If you need a stable sort, package:collection provides insertionSort and mergeSort implementations that are stable.
But comparing might be expensive
Suppose you have a custom comparison function that looks something like:
int compareMyCustomClass(MyCustomClass a, MyCustomClass b) {
var a0 = computeValue(a);
var b0 = computeValue(b);
return a0.compareTo(b0);
}
The sorting process might call computeValue multiple times for the same object, which is particularly wasteful if computeValue() is expensive. In such cases, a Schwartzian transform could be faster (at the expense of using more memory). This approach maps your objects to directly sortable keys, sorts those keys, and extracts the original objects. (This is how Python's sort and sorted functions work.)
Here's one possible implementation:
class _SortableKeyPair<T, K extends Comparable<Object>>
implements Comparable<_SortableKeyPair<T, K>> {
_SortableKeyPair(this.original, this.key);
final T original;
final K key;
#override
int compareTo(_SortableKeyPair<T, K> other) => key.compareTo(other.key);
}
/// Returns a sorted *copy* of [items] according to the computed sort key.
List<E> sortedWithKey<E, K extends Comparable<Object>>(
Iterable<E> items,
K Function(E) toKey,
) {
final keyPairs = [
for (var element in items) _SortableKeyPair(element, toKey(element)),
]..sort();
return [
for (var keyPair in keyPairs) keyPair.original,
];
}
void main() {
final list = <MyCustomClass>[ ... ];
final sorted = sortedWithKeys(list, computeValue);
}
My dartbag package provides such a sortWithKey function (and also a sortWithAsyncKey function if the key needs to be generated asynchronously).
If you want to sort the object "objects" by the property "name" do something like this
objects.sort((a, b) {
return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
});
Immutable extension sortedBy for List.
extension MyIterable<E> on Iterable<E> {
Iterable<E> sortedBy(Comparable key(E e)) =>
toList()..sort((a, b) => key(a).compareTo(key(b)));
}
And use
list.sortedBy((it) => it.name);
Here is my contribution to this good question. If someone is facing difficulty to understand how the #Nate Bosch answer is working & you want to sort your custom model class list then you can do this way.
1. You have to implement Comparable abstract class in your model class.
It has the method compareTo which you have to override.
For example, I have this StudentMarks model class which has marks property in it.
class StudentMarks implements Comparable {
int marks;
StudentMarks({
this.marks,
});
#override
int compareTo(other) {
if (this.marks == null || other == null) {
return null;
}
if (this.marks < other.marks) {
return 1;
}
if (this.marks > other.marks) {
return -1;
}
if (this.marks == other.marks) {
return 0;
}
return null;
}
}
2. Now you can call compareTo method inside the sort method.
void _sortStudents({bool reversed: false}) {
_students.sort((a, b) {
return a.compareTo(b);
});
if (reversed) {
_students = _students.reversed.toList();
}
setState(() {});
}
Refer to this link you want to know more about the Comparable class
https://api.dart.dev/stable/2.1.0/dart-core/Comparable-class.html
Its worked for me:
myList..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
Using Comparatorfunction, sort Users by id.
Comparator<UserModel> sortById = (a, b) => a.id.compareTo(b.id);
users.sort(sortById);
Now we can sort it in reversed/descending order.
users = users.reversed.toList();
To sort it in reverse order :
list.sort((a, b) {
return b.status.toLowerCase().compareTo(a.status.toLowerCase());
});
What's more, you can use Comparable.compare for more clear, for example:
class _Person {
final int age;
final String name;
_Person({required this.age, required this.name});
}
void _test() {
final array = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
];
// ascend with age
// Dean Jack Ben
array.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
// decend with age
// Ben Jack Dean
array.sort((p1, p2) {
return Comparable.compare(p2.age, p1.age);
});
// ascend with name
// Ben Dean Jack
array.sort((p1, p2) {
return Comparable.compare(p1.name, p2.name);
});
}
Similar to #pavel-shorokhovs answer, but strongly typed:
extension IterableExtensions<T> on Iterable<T> {
Iterable<T> sortBy<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
toList()..sort((a, b) => selector(a).compareTo(selector(b)));
Iterable<T> sortByDescending<TSelected extends Comparable<TSelected>>(
TSelected Function(T) selector) =>
sortBy(selector).toList().reversed;
}
i had fpgrowth machine learning output/result with each element of list contains another list and frequency field i was to sort by frequency in descending order so i used a bit of recursion for that try it might work i know i am late but i am posting maybe someone else could benefit.
sort(List<FrequentItem> fqItems) {
int len = fqItems.length;
if(len==2){
if(fqItems[0].frequency>fqItems[1].frequency){
sortedItems.add(fqItems[0]);
sortedItems.add(fqItems[1]);
}else{
sortedItems.add(fqItems[1]);
sortedItems.add(fqItems[0]);
}
return;
}else{
FrequentItem max = fqItems[0];
int index =0;
for(int i=0;i<len-2;i++){
if(max.frequency<fqItems[i+1].frequency){
max = fqItems[i+1];
index = i+1;
}
}
sortedItems.add(max);
fqItems.removeAt(index);
sort(fqItems);
}
}
Step 1: Add compareTo method to class:
class Student {
String? name;
int? age;
Student({this.name, this.age});
int getAge() {
if (age == null) return 0;
return age!;
}
#override
int compareTo(Student other) {
var a = getAge();
var b = other.getAge();
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
}
Step 2: Sorting your list:
By ascending:
studentList.sort((a, b) {
return a.compareTo(b);
});
By descending:
studentList.sort((a, b) {
return b.compareTo(a);
});