Esempio completo in Dart per gestire una libreria di libri con classi, ricerca avanzata, filtri multipli, ordinamento e gestione errori, codice robusto e commen
// Gestione di una Libreria di Libri con Classi e Ricerca Avanzata in Dart
// Classe che rappresenta un libro con attributi base
class Book {
final String title;
final String author;
final int year;
final String genre;
// Costruttore con parametri richiesti
Book({required this.title, required this.author, required this.year, required this.genre});
// Override del metodo toString per una stampa leggibile
@override
String toString() {
return '"$title" di $author ($year) - Genere: $genre';
}
// Metodo per confrontare due libri (utile per evitare duplicati)
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Book &&
other.title.toLowerCase() == title.toLowerCase() &&
other.author.toLowerCase() == author.toLowerCase() &&
other.year == year &&
other.genre.toLowerCase() == genre.toLowerCase();
}
@override
int get hashCode => title.toLowerCase().hashCode ^ author.toLowerCase().hashCode ^ year.hashCode ^ genre.toLowerCase().hashCode;
}
// Classe che gestisce una collezione di libri
class Library {
final List<Book> _books = [];
// Metodo per aggiungere un libro se non è già presente
bool addBook(Book book) {
if (_books.contains(book)) {
// Libro già presente
return false;
}
_books.add(book);
return true;
}
// Metodo per rimuovere un libro, ritorna true se rimosso
bool removeBook(Book book) {
return _books.remove(book);
}
// Metodo per cercare libri con filtri opzionali
// I parametri sono opzionali e la ricerca è case insensitive
List<Book> search({String? title, String? author, int? year, String? genre, String orderBy = 'title'}) {
List<Book> results = _books.where((book) {
final matchTitle = title == null || book.title.toLowerCase().contains(title.toLowerCase());
final matchAuthor = author == null || book.author.toLowerCase().contains(author.toLowerCase());
final matchYear = year == null || book.year == year;
final matchGenre = genre == null || book.genre.toLowerCase() == genre.toLowerCase();
return matchTitle && matchAuthor && matchYear && matchGenre;
}).toList();
// Ordinamento dei risultati
switch (orderBy.toLowerCase()) {
case 'title':
results.sort((a, b) => a.title.toLowerCase().compareTo(b.title.toLowerCase()));
break;
case 'author':
results.sort((a, b) => a.author.toLowerCase().compareTo(b.author.toLowerCase()));
break;
case 'year':
results.sort((a, b) => a.year.compareTo(b.year));
break;
default:
// Se orderBy non riconosciuto, ordina per titolo
results.sort((a, b) => a.title.toLowerCase().compareTo(b.title.toLowerCase()));
}
return results;
}
// Metodo per stampare tutti i libri presenti
void printAllBooks() {
if (_books.isEmpty) {
print('La libreria è vuota.');
return;
}
print('Libri presenti nella libreria:');
for (var book in _books) {
print('- $book');
}
}
}
// Funzione main per dimostrare l'uso della libreria
void main() {
final library = Library();
// Aggiunta di alcuni libri
library.addBook(Book(title: 'Il nome della rosa', author: 'Umberto Eco', year: 1980, genre: 'Storico'));
library.addBook(Book(title: '1984', author: 'George Orwell', year: 1949, genre: 'Distopico'));
library.addBook(Book(title: 'Il Signore degli Anelli', author: 'J.R.R. Tolkien', year: 1954, genre: 'Fantasy'));
library.addBook(Book(title: 'Harry Potter e la Pietra Filosofale', author: 'J.K. Rowling', year: 1997, genre: 'Fantasy'));
library.addBook(Book(title: 'Il piccolo principe', author: 'Antoine de Saint-Exupéry', year: 1943, genre: 'Fiaba'));
// Stampa tutti i libri
library.printAllBooks();
print('');
// Ricerca avanzata: tutti i libri fantasy ordinati per anno
print('Ricerca: libri di genere Fantasy ordinati per anno:');
var fantasyBooks = library.search(genre: 'Fantasy', orderBy: 'year');
for (var book in fantasyBooks) {
print('- $book');
}
print('');
// Ricerca con più filtri: autore contiene "Umberto" e anno 1980
print('Ricerca: libri di autore contenente "Umberto" e anno 1980:');
var filteredBooks = library.search(author: 'Umberto', year: 1980);
for (var book in filteredBooks) {
print('- $book');
}
print('');
// Tentativo di aggiungere un libro duplicato
bool added = library.addBook(Book(title: '1984', author: 'George Orwell', year: 1949, genre: 'Distopico'));
print(added ? 'Libro aggiunto con successo.' : 'Libro già presente, non aggiunto.');
print('');
// Rimozione di un libro
bool removed = library.removeBook(Book(title: 'Il piccolo principe', author: 'Antoine de Saint-Exupéry', year: 1943, genre: 'Fiaba'));
print(removed ? 'Libro rimosso con successo.' : 'Libro non trovato, impossibile rimuovere.');
print('');
// Stampa finale della libreria
library.printAllBooks();
}Classe Book: rappresenta un libro con titolo, autore, anno di pubblicazione e genere.
Classe Library: gestisce una lista di libri con metodi per aggiungere, rimuovere, cercare e ordinare.
Ricerca avanzata: metodo search che accetta filtri multipli (titolo, autore, anno, genere) e restituisce i libri corrispondenti.
Ordinamento: possibilità di ordinare i risultati per titolo, autore o anno.
Gestione errori: controllo su input e metodi per evitare duplicati o rimozioni di libri non esistenti.
Ambiente: Dart SDK 2.12+ (null safety abilitata).
Dipendenze: nessuna dipendenza esterna, solo librerie standard Dart.
Configurazione: eseguire da terminale con 'dart run nomefile.dart'.
Output: stampa su console dei risultati delle operazioni.