Gary Frewin
Gary Frewin

Reputation: 565

Flutter Bloc events not happening in correct order

Ok, perhaps I am using this incorrectly. I want to save a note in my app, and then update the list view on the home screen so it shows the new note... sounds simple.

However... the save note event is happening last, and the refetch notes on the homescreen is happening first, despite them being the other way around in the code:

Edit Note Screen:

   void handleSaveNewNote() async {
    BlocProvider.of<NoteDetailBloc>(context).add(SaveNewNoteEvent(note: currentNote)); //this is happening last
    resetAfterSave();
  }

  void resetAfterSave() async {
    BlocProvider.of<NoteListBloc>(context)..add(RefreshNoteListEvent()); /// this is happening first
    Navigator.pop(context);
  }

Note Detail Bloc:

if (event is SaveNewNoteEvent) {
  note = await notesRepository.addNote(event.note);
  print('new note is now saved'); // this shows as the very last print statement, but should be the first
  yield NoteDetailLoadedState(note: note);
}

Note List Bloc:

if (event is RefreshNoteListEvent) {
  yield initialState;
  List<NotesModel> notesList = await notesRepository.fetchNotes();
  print('Bloc: i have awaited fetching $notesList'); // this shows as the very first print statement, but should be last... argh!
  yield NoteListLoadedState(notesList: notesList);
}

I'm pulling my hair out. Why is the last event happening first and the first event happening last?

Upvotes: 1

Views: 816

Answers (1)

Gary Frewin
Gary Frewin

Reputation: 565

So, this is perhaps only a partial answer... I'd still like to understand the issue above and why it is not awaiting the note being saved before refeshing the list...

However, for others with the issue, I fixed it by adding a bloclistener above the blocbuilder that builds the note list. Like this:

    BlocListener<NoteDetailBloc, NoteDetailState>(
                listener: (context, state) {
                  if (state is NoteAddedState) {
                    BlocProvider.of<NoteListBloc>(context).add(RefreshNoteListEvent());
                  }
                },
                child: BlocBuilder<NoteListBloc, NoteListState>(builder: (context, state) {
                  if (state is NoteListInitialState) {...

Then changed the yield state in the NoteDetailBloc for whenever a new note is added:

if (event is SaveNewNoteEvent) {
  note = await notesRepository.addNote(event.note);
  yield NoteAddedState(); <-- changed this event. 
}

So, the listener listens for the detail bloc to emit a 'NoteAddedState'. When it does, it adds a refresh event to the list bloc.

Upvotes: 1

Related Questions