1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-12 07:48:55 +00:00

Move library to a top-level variable, since it never changes (#887)

This commit is contained in:
Kevin Moore
2021-08-26 16:18:40 -07:00
committed by GitHub
parent ecf716dcab
commit c9688ca34b
8 changed files with 77 additions and 114 deletions

View File

@@ -7,7 +7,7 @@ import 'book.dart';
class Author {
final int id;
final String name;
final List<Book> books;
final List<Book> books = <Book>[];
Author(this.id, this.name, this.books);
Author(this.id, this.name);
}

View File

@@ -7,9 +7,9 @@ import 'author.dart';
class Book {
final int id;
final String title;
late final Author author;
final Author author;
final bool isPopular;
final bool isNew;
Book(this.id, this.title, this.isPopular, this.isNew);
Book(this.id, this.title, this.isPopular, this.isNew, this.author);
}

View File

@@ -2,11 +2,31 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:collection/collection.dart';
import 'author.dart';
import 'book.dart';
final libraryInstance = Library()
..addBook(
title: 'Left Hand of Darkness',
authorName: 'Ursula K. Le Guin',
isPopular: true,
isNew: true)
..addBook(
title: 'Too Like the Lightning',
authorName: 'Ada Palmer',
isPopular: false,
isNew: true)
..addBook(
title: 'Kindred',
authorName: 'Octavia E. Butler',
isPopular: true,
isNew: false)
..addBook(
title: 'The Lathe of Heaven',
authorName: 'Ursula K. Le Guin',
isPopular: false,
isNew: false);
class Library {
final List<Book> allBooks = [];
final List<Author> allAuthors = [];
@@ -17,18 +37,17 @@ class Library {
required bool isPopular,
required bool isNew,
}) {
var author =
allAuthors.firstWhereOrNull((author) => author.name == authorName);
var book = Book(allBooks.length, title, isPopular, isNew);
var author = allAuthors.firstWhere(
(author) => author.name == authorName,
orElse: () {
final value = Author(allAuthors.length, authorName);
allAuthors.add(value);
return value;
},
);
var book = Book(allBooks.length, title, isPopular, isNew, author);
if (author == null) {
author = Author(allAuthors.length, authorName, [book]);
allAuthors.add(author);
} else {
author.books.add(book);
}
book.author = author;
author.books.add(book);
allBooks.add(book);
}