Collections
- Dart course
- Beginner
- Lesson 114/116
- 6 min
Write data management with List and Map.
Collections
Instead of holding books in separate variables we gather them in a List. A List<Book> carries many books in order. With final books = <Book>[...]; you create a list, add with .add(...) and loop with a for.
In this lesson we will first gather a few books in a List and print the count and the first book. You get the length with .length; for example books.length gives the book count. A specific element is fetched by index: books[0]. In later lessons we will walk the whole list with a for loop.
Adding books to a List
To add an element to a List use .add(...) or .addAll([...]). You can also initialize the list directly at declaration: final books = <Book>[Book("Crime"), Book("Les Mis")];. This is the idiomatic way to set up a list.
You get the length with .length; for example books.length gives the book count. A specific element is fetched by index: books[0]. books[0].title yields the first book's title. With these tools you can both count and access a collection.
Practice List the books
The Library and Book classes plus a single book are already defined in the code below. In main create a list of two books with final books = <Book>[Book("Crime and Punishment"), Book("Les Mis")];. Print the count with print("Count: ${books.length}") and the first book's title with print("First: ${books[0].title}").
Starter code
class Library {
String name;
Library(this.name);
void info() {
print("Library: $name");
}
}
class Book {
String title;
Book(this.title);
}
void main() {
final lib = Library("City");
lib.info();
final b = Book("Crime and Punishment");
print("New book: ${b.title}");
// create a list of two books, print count and first book
}Sample solution
class Library {
String name;
Library(this.name);
void info() {
print("Library: $name");
}
}
class Book {
String title;
Book(this.title);
}
void main() {
final lib = Library("City");
lib.info();
final b = Book("Crime and Punishment");
print("New book: ${b.title}");
final books = <Book>[Book("Crime and Punishment"), Book("Les Mis")];
print("Count: ${books.length}");
print("First: ${books[0].title}");
}Expected output
Library: City New book: Crime and Punishment Count: 2 First: Crime and Punishment
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one holds many books in order?
final books = <Book>[];
books.add(Book("Crime"));- List<Book>
- Map<Book>
- Set<Book> Correct answer
- Book
Explanation: List<Book> carries many books in order.
2 The list length
final books = <Book>[Book("Crime"), Book("Les Mis")];
print(books.____);
final books = <Book>[Book("Crime"), Book("Les Mis")];
print(books.length);
Explanation: the list length is read with length.
3 Match collections
| Term | Meaning |
|---|---|
List<Book> |
ordered book list |
.add(book) |
appends to the list |
.length |
the count |
books[0] |
first element |