How to use dispose with flutter bloc?

Issue

I have this stateful widget which uses a bloc called RecorderBloc:

class _RecorderScreenWidgetState extends State<RecorderScreenWidget> {
  late final RecorderBloc _recorderBloc;

  @override
  void initState() {
    super.initState();
    _recorderBloc = serviceLocator.get<RecorderBloc>();
  }

  @override
  void dispose() {
    _recorderBloc.add(RecorderEvent.dispose());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
                 //.....ommitted code
   }

As you can see I need to dispose some members of the bloc after I finish from them, and that is done by adding a dispose event.

But I don’t know if defining the bloc as a member variable of the stateful widget is the right approach?

If not, then how can I get the instance of the bloc inside the dispose() method of the StatefulWidget to add a dispose event?

Solution

As far as I know there is no need for defining a dispose event. The Bloc class has a close function which will be called when the provider widget (BlocProvider) state is being disposed. You can override that function inside of your BLoC and do whatever is needed.

class MyBloc extends Bloc<MyBlocState> {
  @override
  Future<void> close() {
    // dispose
    return super.close();
  }
}

Answered By – Amir_P

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *