fnotes/lib/persistent_notes_bloc.dart

79 lines
2.1 KiB
Dart
Raw Permalink Normal View History

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fnotes/database.dart';
import 'package:fnotes/note.dart';
class PersistentNotesBloc
extends Bloc<PersistentNotesEvent, PersistentNotesState> {
PersistentNotesBloc() : super(PersistentNotesState.init()) {
on<LoadNotesEvent>(loadAllNotes);
on<NoteEntered>(storeNote);
on<NoteDismissed>(deleteNote);
}
void storeAllNotes(
PersistentNotesEvent event, Emitter<PersistentNotesState> emit) {}
void loadAllNotes(
PersistentNotesEvent event, Emitter<PersistentNotesState> emit) async {
List<Note> list = [];
await database.select(database.persistentNote).get().then(
(value) {
list = value.map((row) {
return Note.withId(id: row.id, content: row.content);
}).toList();
},
);
emit(PersistentNotesState(notes: list));
}
void storeNote(NoteEntered event, Emitter<PersistentNotesState> emit) async {
await database
.into(database.persistentNote)
.insert(PersistentNoteCompanion.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(PersistentNotesState(notes: newNotes));
}
void deleteNote(NoteDismissed event, Emitter<PersistentNotesState> emit) {
(database.delete(database.persistentNote)
..where((tbl) => tbl.id.equals(event.note.id)))
.go();
var newNotes =
state.notes.where((note) => note.id != event.note.id).toList();
emit(PersistentNotesState(notes: newNotes));
}
}
class PersistentNotesEvent {}
class LoadNotesEvent extends PersistentNotesEvent {}
class NoteEntered extends PersistentNotesEvent {
final Note note;
NoteEntered(this.note);
}
class NoteDismissed extends PersistentNotesEvent {
final Note note;
NoteDismissed(this.note);
}
class PersistentNotesState {
List<Note> notes = List.empty(growable: true);
PersistentNotesState({required this.notes});
factory PersistentNotesState.init() {
return PersistentNotesState(notes: []);
}
}