Summary - Lists
- Dart course
- Beginner
- Lesson 58/116
- 5 min
Combine add, map and where to write a class list.
Summary - Lists
In this group you learned List creation, index access, add/remove, length/contains and the map/where methods. Now we will combine them to write a class-list application.
The app will append grades to a list with add and filter those 50 and above with where. This structure combines data entry and filtering; it is the core of a real grade-tracking app.
Plan
We will build the class-list app step by step: (1) declare an empty List<int>; (2) add a few grades with add; (3) filter those 50 and above with where; (4) convert the result to a List with .toList(); (5) print with print.
This structure is the skeleton of a real grade-tracking app too. Dropping low grades and listing the passing ones is common in schools and workplaces. Remember to convert the Iterable returned by where with .toList().
Practice Class list app
Declare an empty int list with var grades = <int>[];. Add four grades with grades.add(40);, grades.add(55);, grades.add(70);, grades.add(30);. Declare a variable passing and assign the result of grades.where((g) => g >= 50).toList() to it. Print passing with print(passing);. The output on a single line must be [55, 70].
Starter code
// Declare grades, add with add, filter with where and printSample solution
var grades = <int>[];
grades.add(40);
grades.add(55);
grades.add(70);
grades.add(30);
var passing = grades.where((g) => g >= 50).toList();
print(passing);Expected output
[55, 70]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the add call
var grades = <int>[];
grades____;
grades.add(90);
print(grades);
var grades = <int>[];
grades.add(85);
grades.add(90);
print(grades);
Explanation: .add(85) appends 85 to the list.
2 Which methods fit adding, filtering 50+ and transforming?
// class list- add + where + map Correct answer
- add + map + fold
- remove + length + contains
- add + sort + print
Explanation: add appends, where filters, map transforms.