CodeBlanks Logo Icon CodeBlanks

Collections

Write data filtering with List, Map and Stream.

Collections

You manage tasks with a List<Task>. It holds many tasks in one structure; a Map can group them by category.

You build a list with var tasks = <Task>[Task('Code write'), Task('Test write', done: true)];. tasks.length gives the count.

tasks.where((t) => t.isDone) filters the completed ones, and .toList() turns them into a list.

Filtering with where

Typical usage: var done = tasks.where((t) => t.isDone).toList(); takes the completed ones into a new list.

Then print(done.length) prints how many are completed. where returns an iterable; toList() turns it into a concrete list.

This is the basis of functional collection handling; you filter without writing a loop.

Practice Tasks with List<Task>

In main define var tasks = <Task>[Task('Code write'), Task('Test write', done: true)];. Filter the completed ones with var done = tasks.where((t) => t.isDone).toList();. Print print(done.length).

Starter code

main.dart
abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() {
  // create a tasks list, filter with where, print length
}

Sample solution

main.dart
abstract class Trackable {
  bool get isDone;
}

class Task implements Trackable {
  final String title;
  bool done;
  Task(this.title, {this.done = false});

  @override
  bool get isDone => done;
}

void main() {
  var tasks = <Task>[Task('Code write'), Task('Test write', done: true)];
  var done = tasks.where((t) => t.isDone).toList();
  print(done.length);
}

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Collection operations

Term Meaning
List<Task> Task list
tasks.length Count
where(...) Filtering
toList() To a list

2 How do you filter the completed tasks?

  • tasks.where((t) => t.isDone) Correct answer
  • tasks.find(...)
  • tasks.filter(...)
  • tasks.select(...)

Explanation: where filters elements by a condition.

3 List<Task> declaration

Question
var tasks = ____[Task('Kod yaz'), Task('Test yaz', done: true)];
Answer
var tasks = <Task>[Task('Kod yaz'), Task('Test yaz', done: true)];

Explanation: <Task>[...] is a typed list literal.

All lessons in Intermediate