Dart
Checking out
Write the checkout flow with checkout and return methods.
checkout and returnBook
To lend a book we write a checkout method; to take it back we write a returnBook method. Both take an index and change the borrowed field of the matching book.
Example: void checkout(int index) { books[index].borrowed = true; }. This method sets borrowed to true for the book at the given index. returnBook sets it to false.
This structure is the basis of lending. When a book is lent borrowed becomes true; when returned it becomes false. The index parameter tells which book is processed.
Taking a book back
The returnBook method does the reverse of checkout. With books[index].borrowed = false it marks the book as returned. This way the same book can be lent again.
Example flow: lib.addBook(Book('Les Miserables'));, lib.checkout(0);, print(lib.books[0].borrowed); gives true. Then lib.returnBook(0);, print(lib.books[0].borrowed); gives false.
These two methods form the lending cycle together. A book goes out, comes back, goes out again. This is how a library system works.
Exercise Add checkout and returnBook
Add void checkout(int index) and void returnBook(int index) methods to the Library class. Inside checkout write books[index].borrowed = true; inside returnBook write books[index].borrowed = false. The main already calls checkout and returnBook.
Show example solution
class Book {
String title;
bool borrowed = false;
Book(this.title);
}
class Library {
List<Book> books = [];
void addBook(Book b) {
books.add(b);
}
void checkout(int index) {
books[index].borrowed = true;
}
void returnBook(int index) {
books[index].borrowed = false;
}
}
void main() {
var lib = Library();
lib.addBook(Book('Les Miserables'));
lib.checkout(0);
print(lib.books[0].borrowed);
lib.returnBook(0);
print(lib.books[0].borrowed);
}
Test yourself
-
Match the checkout parts
- int index
- Index parameter
- books[index]
- Book at index
- .borrowed = true
- Lend out
- .borrowed = false
- Take back
-
What does checkout(0) do?
void checkout(int index) {
books[index].borrowed = true;
}
- Lends all books out
- Removes the first book
- Sets borrowed of the first book to true
- Prints the list
Show answer
Sets borrowed of the first book to true — checkout(0) sets borrowed of the book at index 0 to true.
-
The borrowed assignment
void checkout(int index) {
books[index].borrowed = ____;
}
Show answer
void checkout(int index) {
books[index].borrowed = true;
}
Next lesson: Search and filter