0

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.

  • Does this answer your question? [The method '\[\]' can't be unconditionally invoked because the receiver can be 'null'](https://stackoverflow.com/questions/67575893/the-method-cant-be-unconditionally-invoked-because-the-receiver-can-be-nu) – George Apr 18 '22 at 20:34

1 Answers1

0

The error occurs because your variable TasksWithSameListId is nullable. Also never initialized. To fix your issue you can initialize it and make it non nullable.

List<Task> getTasksByParentId(int parentId) {
  final List<Task> tasksWithSameId = [];

  if (_tasks.isNotEmpty) {
    for (var item in _tasks) {
      if (item.parentId == parentId) {
        tasksWithSameId.add(item);
      }
    }
  }
  return tasksWithSameId;
}

A better approach is to use where to filter your list.

List<Task> getTasksByParentId(int parentId) {
  return _tasks.where((item) => item.parentId == parentId).toList();
}
quoci
  • 2,940
  • 1
  • 9
  • 21