I'm new to programming and I'm learning flutter. I'm trying to loop through a list of _tasks to get the tasks that has the parentId I need.
- Error: The method 'add' can't be unconditionally invoked because the receiver can be 'null'.
- Question 1: I already make sure the item is not null in the if statement, but the add method still think the item could be null.. How do I prevent this?
- Question 2: If there a better way to get a list of Tasks without using for in loop?
class TaskData extends ChangeNotifier {
List<Task> _tasks = [
Task(parentId: 1, name: "Task1"),
Task(parentId: 1, name: "Task2"),
Task(parentId: 2, name: "Task3"),
Task(parentId: 3, name: "Task3"),
];
List<Task>? getTasksByParentId(int parentId) {
List<Task>? TasksWithSameListId;
if (_tasks.isNotEmpty) {
for (var item in _tasks) {
if (item.parentId == parentId) {
TasksWithSameListId.add(item);
}
}
}
}
Expecting result: when calling function getTasksByParentId, it should return a list of Tasks that has the same parentId.