CodeBlanks Logo Icon CodeBlanks

Library class

Set up collection management with the Library class.

Library class and addBook

Now let's write the Library class that stores books. It has a List<Book> field and an addBook method. Each added book grows the list.

Example: class Library { List<Book> books = []; void addBook(Book b) { books.add(b); } }. Here books starts as an empty list. The addBook method takes a Book and appends it.

With this design you can add as many books as you want. The next lessons add checkout and search methods.

Initializing List<Book>

The line List<Book> books = []; creates an empty Book list. In Dart [] means an empty list. Because the type is Book, only Book objects can be added.

This gives type safety: books.add('text') is a compile error because 'text' is not a Book. Only books.add(Book(...)) is valid.

Read the list length with books.length. It tells you how many books are stored.

Practice Add the Library class and addBook

The Book class is already defined. Now define a Library class with a List<Book> books = [] field and a void addBook(Book b) method. Inside the method write books.add(b). In main create a Library, add two books and print lib.books.length.

Starter code

main.dart
class Book {
  String title;
  bool borrowed = false;
  Book(this.title);
}

// define the Library class: book list and add method

void main() {
  // create a Library instance, add two books and print the count
}

Sample solution

main.dart
class Book {
  String title;
  bool borrowed = false;
  Book(this.title);
}

class Library {
  List<Book> books = [];
  void addBook(Book b) {
    books.add(b);
  }
}

void main() {
  var lib = Library();
  lib.addBook(Book('Les Miserables'));
  lib.addBook(Book('Crime and Punishment'));
  print(lib.books.length);
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the addBook method do?

main.dart
void addBook(Book b) {
  books.add(b);
}
  • Removes the book
  • Appends the book to the list Correct answer
  • Prints the book
  • Lends the book out

Explanation: addBook appends the given book to the list.

2 The books.add call

Question
class Library {
  List<Book> books = [];
  void addBook(Book b) {
    ____.add(b);
  }
}
Answer
class Library {
  List<Book> books = [];
  void addBook(Book b) {
    books.add(b);
  }
}

Explanation: books.add(b) appends the book.

3 Match the Library parts

Term Meaning
List<Book> Book list type
books = [] Empty start
addBook(Book b) Add method
books.add(b) Append to list

All lessons in Intermediate