import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:fnotes/database.dart'; import 'package:fnotes/note.dart'; class PersistentNotesBloc extends Bloc { PersistentNotesBloc() : super(PersistentNotesState.init()) { on(loadAllNotes); on(storeNote); on(deleteNote); } void storeAllNotes( PersistentNotesEvent event, Emitter emit) {} void loadAllNotes( PersistentNotesEvent event, Emitter emit) async { List 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 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 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 notes = List.empty(growable: true); PersistentNotesState({required this.notes}); factory PersistentNotesState.init() { return PersistentNotesState(notes: []); } }