fnotes/lib/persistence_bloc.dart

80 lines
2.1 KiB
Dart
Raw Normal View History

2024-03-17 17:38:57 +00:00
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fnotes/database.dart';
import 'package:fnotes/note.dart';
2024-03-17 17:38:57 +00:00
class PersistenceBloc extends Bloc<PersistenceEvent, PersistenceState> {
static final database = AppDatabase();
2024-03-17 17:38:57 +00:00
PersistenceBloc() : super(PersistenceState.init()) {
on<StoreNotesEvent>(storeAllNotes);
on<LoadNotesEvent>(loadAllNotes);
on<NoteEntered>(storeNote);
on<NoteDismissed>(deleteNote);
2024-03-17 17:38:57 +00:00
}
void storeAllNotes(PersistenceEvent event, Emitter<PersistenceState> emit) {}
void loadAllNotes(
PersistenceEvent event, Emitter<PersistenceState> emit) async {
List<Note> list = [];
await database.select(database.noteTable).get().then(
(value) {
list = value.map((row) {
return Note.withId(id: row.id, content: row.content);
}).toList();
},
);
emit(PersistenceState(notes: list));
}
void storeNote(NoteEntered event, Emitter<PersistenceState> emit) async {
await database.into(database.noteTable).insert(NoteTableCompanion.insert(
id: event.note.id,
content: event.note.content,
));
var newNotes = state.notes;
newNotes.add(Note.withId(id: event.note.id, content: event.note.content));
emit(PersistenceState(notes: newNotes));
}
void deleteNote(NoteDismissed event, Emitter<PersistenceState> emit) {
(database.delete(database.noteTable)
..where((tbl) => tbl.id.equals(event.note.id)))
.go();
var newNotes =
state.notes.where((note) => note.id != event.note.id).toList();
emit(PersistenceState(notes: newNotes));
}
2024-03-17 17:38:57 +00:00
}
class PersistenceEvent {}
class LoadNotesEvent extends PersistenceEvent {}
class StoreNotesEvent extends PersistenceEvent {}
class NoteEntered extends PersistenceEvent {
final Note note;
NoteEntered(this.note);
}
class NoteDismissed extends PersistenceEvent {
final Note note;
NoteDismissed(this.note);
}
2024-03-17 17:38:57 +00:00
class PersistenceState {
List<Note> notes = List.empty(growable: true);
2024-03-17 17:38:57 +00:00
PersistenceState({required this.notes});
2024-03-17 17:38:57 +00:00
factory PersistenceState.init() {
return PersistenceState(notes: []);
2024-03-17 17:38:57 +00:00
}
}