Reputation: 113
I'm building a TODO application using Flutter.
What I need to do is to sort tasks stored in List
using my own compare method (completed tasks must be at the bottom).
The list I need to sort:
var taskWidgets = List<Widget>();
Elements of taskWidgets
list are TaskCard
class objects
class TaskCard extends StatefulWidget {
My compare method:
int compareTasks(TaskCard a, TaskCard b) {
if (a.state._checked == b.state._checked) {
return 0;
}
if (a.state._checked && !b.state._checked) {
return 1;
}
return -1;
}
This is how I sort my list:
taskWidgets.sort(compareTasks);
After doing all that I get the following error:
type '(TaskCard, TaskCard) => int' is not a subtype of type '((Widget, Widget) => int)?'
I tried to change compare function
int compareTasks(Widget a, Widget b) {
if (a.state._checked == b.state._checked) {
return 0;
}
if (a.state._checked && !b.state._checked) {
return 1;
}
return -1;
}
But then I got another error
lib/main.dart:98:11: Error: The getter 'state' isn't defined for the class 'Widget'.
- 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../AppData/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'state'.
if (a.state._checked == b.state._checked) {
So all in all, the question is: How do I properly sort a List of TaskCard objects using my own compare function?
Upvotes: 0
Views: 916
Reputation: 516
in the case you know all taskWidgets
elements are of the type TaskCard
you can change taskWidgets
to be of type List<TaskCard>
in order to make your first compare method work.
if you want to keep your list of type List<Widget>
, you need to manualy check if your widgets are of type Taskcard
, and take in to consideration the case in which they aren't:
int compareTasks(Widget a, Widget b) {
if (!(a is TaskCard)) {
return -1; // if a is not of type Taskcard, make it go before b
}
if (!(b is TaskCard)) {
return 1; // if a is a TaskCard and b is not Taskcard, make b go before a
}
TaskCard taskA = a as TaskCard;
TaskCard taskB = b as TaskCard;
if (taskA.state._checked == taskB.state._checked) {
return 0;
}
if (taskA.state._checked && !taskB.state._checked) {
return 1;
}
return -1;
}
Upvotes: 2