Does Flutter BLoC (flutter_bloc) have an equivalent to onDispose?

Issue

I have created a BLoC using flutter_bloc, on which I listen to a stream. When the parent widget gets disposed (and therefore the BLoC object), I would like to close my stream.

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  //..bloc params..//

  ChatBloc(this.chatId) {
    this.add(MarkAsRead());
    subscription = messagesFirestoreRepository.chatMessages(chatId).listen((messages) {
      this.add(UpdateMessages(messages));
    });
  } //I WANT TO CLOSE THIS WHEN THE BLOC GETS DISPOSED OR DEINITED

  //..other stuff..//
}

Does flutter_bloc or ‘Any’ class have the equivalent of dispose or Swift’s deinit?

Thanks!

Solution

You can override the close method:

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  @override
  Future<void> close() {
    // Release resources here
    super.close();
  }
}

Answered By – Rémi Rousselet

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

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