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