Search code examples
flutterblocflutter-bloc

flutter_bloc 8: what is the best practice for listening to state changes from another bloc


What is the best practice for listening to another bloc’s state changes?

This answer was relevant in previous version, but it doesn’t work in version 8 (.listen method doesn’t exist anymore on a bloc): https://stackoverflow.com/a/62785980/160919

FilteredTodosBloc({@required this.todosBloc}) {
  todosSubscription = todosBloc.listen((state) {
    if (state is TodosLoadSuccess) {
      add(TodosUpdated((todosBloc.state as TodosLoadSuccess).todos));
    }
});}

What is the recommended approach to listen to a state change from another bloc in flutter_bloc 8?


Solution

  • State stream is now exposed via stream getter, so you can still use almost the same code:

    FilteredTodosBloc({required this.todosBloc}) {
      todosSubscription = todosBloc.stream.listen((state) {
        if (state is TodosLoadSuccess) {
          add(TodosUpdated((todosBloc.state as TodosLoadSuccess).todos));
        }
    });}