Files
hlaskovnik-reimagined/frontend/lib/provider/quote_provider.dart
T
2026-03-22 20:05:31 +01:00

69 lines
1.5 KiB
Dart

// gets all quotes from the database and returns them in a list
import 'package:flutter/material.dart';
import 'package:frontend/model/quote.dart';
import 'package:frontend/repository/quote_repository.dart';
class QuoteProvider extends ChangeNotifier {
List<Quote> _quotes = [];
bool _loading = false;
String? _error;
List<Quote> get quotes => _quotes;
bool get loading => _loading;
String? get error => _error;
final QuoteRepository repo = QuoteRepository();
QuoteProvider() {
readQuotes(); // auto-load on creation
}
Future<void> readQuotes() async {
_loading = true;
_error = null;
notifyListeners();
try {
_quotes = await repo.readQuotes();
} catch (e) {
_error = e.toString();
}
_loading = false;
notifyListeners();
}
Future<void> createQuote(Quote quote) async {
final newQuote = await repo.createQuote(quote);
_quotes.add(newQuote);
notifyListeners();
}
Future<void> updateQuote(Quote quote) async {
try {
_loading = true;
notifyListeners();
final updated = await repo.updateQuote(quote);
final index = _quotes.indexWhere((q) => q.id == quote.id);
if (index != -1) {
final newList = List<Quote>.from(_quotes);
newList[index] = updated;
_quotes = newList;
}
} finally {
_loading = false;
notifyListeners();
}
}
Future<void> deleteQuote(Quote quote) async {
await repo.deleteQuote(quote);
_quotes.removeWhere((q) => q.id == quote.id);
notifyListeners();
}
}