Dart
Collections
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.
Exercise 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}").
Show example 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}");
}
Test yourself
-
Which one holds many books in order?
final books = <Book>[];
books.add(Book("Crime"));
- List<Book>
- Map<Book>
- Set<Book>
- Book
Show answer
Set<Book> — List<Book> carries many books in order.
-
The list length
final books = <Book>[Book("Crime"), Book("Les Mis")];
print(books.____);
Show answer
final books = <Book>[Book("Crime"), Book("Les Mis")];
print(books.length);
-
Match collections
- List<Book>
- ordered book list
- .add(book)
- appends to the list
- .length
- the count
- books[0]
- first element
Next lesson: Error handling