【问题标题】:Flutter Bloc events not happening in correct orderFlutter Bloc 事件未按正确顺序发生
【发布时间】:2020-06-28 14:51:06
【问题描述】:

好吧,也许我用错了。我想在我的应用中保存一个笔记,然后更新主屏幕上的列表视图,以便它显示新的笔记...听起来很简单。

但是...保存笔记事件最后发生,主屏幕上的重新获取笔记首先发生,尽管它们在代码中是相反的:

编辑笔记屏幕:

   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);
  }

注意细节块:

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);
}

笔记列表块:

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);
}

我正在拔头发。为什么最后一个事件先发生,第一个事件最后发生?

【问题讨论】:

    标签: flutter bloc


    【解决方案1】:

    所以,这可能只是部分答案...我仍然想了解上面的问题以及为什么在刷新列表之前不等待保存笔记...

    但是,对于其他有问题的人,我通过在构建笔记列表的 blocbuilder 上方添加一个 bloclistener 来修复它。像这样:

        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) {...
    

    然后在 NoteDetailBloc 中为每次添加新注释更改屈服状态:

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

    因此,侦听器侦听详细信息块以发出“NoteAddedState”。当它这样做时,它会向列表块添加一个刷新事件。

    【讨论】:

      猜你喜欢
      • 2022-07-26
      • 2016-11-23
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多