Dart
Putting it together
Combine all parts into a working final app.
Putting it together
In the final lesson we combine all the parts: the Library class, the Book class, the book list and error handling with try/catch. We will get a working library console application; it prints all books and gives a friendly message on error.
This combines all the beginner fundamentals in a real task: class definition, constructor, field access, List and a for loop, resilience with try/catch. You will see this pattern again and again in later projects; so learning it well now matters.
The working app
The code below already has the classes, the list and try/catch. The only missing piece is the for loop that prints all books. You will add this loop before the try block; so first all books are listed, then the out-of-range access is tried.
When you write for (final book in books) { print("Book: ${book.title}"); } each book's title appears. try/catch is already in place; so the app both lists and catches errors. This is a small but complete example of the beginner level.
Exercise Working library
The classes, the list and try/catch are already defined in the code below. In main add a for loop before the try block: for (final book in books) { print("Book: ${book.title}"); }. So first all books are printed, then the out-of-range access is tried.
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}");
for (final book in books) {
print("Book: ${book.title}");
}
try {
print(books[5].title);
} catch (e) {
print("book not found");
}
}
Test yourself
-
The for loop connector
for (final book ____ books) {
print("Book: ${book.title}");
}
Show answer
for (final book in books) {
print("Book: ${book.title}");
}
-
What does the for loop do in this project?
for (final book in books) {
print("Book: ${book.title}");
}
- Prints every book's title
- Adds a book to the list
- Catches the error
- Changes the library name
Show answer
Prints every book's title — the for loop prints every book's title.
-
Match the final parts
- class
- defines an object
- List<Book>
- gathers books
- for
- walks the list
- try/catch
- adds resilience
Next lesson: Beginner section exam