Listen to Events instead of States with Flutter BLOC

Issue

I am using the Flutter BLOC library (https://pub.dev/packages/bloc)
I know there is a way to “listen to” BLOC states changes (with the listen() function)

chatBloc.listen((chatState) async {
      if (chatState is ChatStateInitialized) {
        // do something
      }
    });

But is there a way to listen to BLOC events instead ? Just like I would do with a classical StreamController ?
Thanks to all who will be willing to help 🙂

Julien

Solution

Yes, you can listen to BLoC events by below code:

BlocSupervisor.delegate = MyBlocDelegate();

And your main.dart similar to below code:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  BlocSupervisor.delegate = MyBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: BlocProvider<CounterBLoC>(
        create: (ctx) => CounterBLoC(),
        child: TestBlocWidget(),
      ),
    );
  }
}

Here is your bloc_delegate.dart for listen to events of BLoC:

import 'package:bloc/bloc.dart';

class MyBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    print(event);
    super.onEvent(bloc, event);
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stackTrace) {
    print(error);
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    print(transition);
    super.onTransition(bloc, transition);
  }
}

Answered By – Taleb

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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