Search code examples
flutterdartbloc

MultiBlocProvider does not add event


I had all my BlocProviders nested what worked but didn't look very good, so i rewrote it to a MultiBlocProvider as seen in the Code below. The problem now is, that the event and with that the _initialiazeDatabase() function in the listener doesn't get called. I already saw some posts where i need to set lazy to false which i did, but still not work.


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => AppBloc()..add(AppStartedEvent()),
          lazy: false,
          child: BlocListener<AppBloc, AppState>(
            listener: (context, state) {
              if (state is AppStarted) {
                _initializeDatabase();
              }
            },
          ),
        ),
        BlocProvider(
          create: (context) => GroupOverviewBloc()..add(LoadPlayers()),
          lazy: false,
          child: BlocListener<GroupOverviewBloc, PlayerOverviewState>(
            listener: (context, state) {
              if (state is GroupAdded || state is GroupDeleted) {
                context.read<GroupOverviewBloc>().add(LoadPlayers());
              }
            },
          ),
        ),
        BlocProvider(
          create: (context) => PlayerFormCubit(),
        ),
        BlocProvider(
          create: (context) => HealthCubit(),
        ),
        BlocProvider(
          create: (context) => ManaCubit(),
        ),
      ],
      child: const MaterialApp(
        home: PlayerOverview(),
      ),
    );
  }

  Future<void> _initializeDatabase() async {
    await DBHelper.instance.database;
  }
}

class AppBloc extends Bloc<AppEvent, AppState> {
  AppBloc() : super(AppInitial()) {
    on<AppStartedEvent>((event, emit) {
      emit(AppStarted());
    });
  }
}

abstract class AppState {}

class AppInitial extends AppState {}

class AppStarted extends AppState {}

abstract class AppEvent {}

class AppStartedEvent extends AppEvent {}

Solution

  • Could fix it by wrapping the MaterialApp with a MultiBloCListener and putting the listeners in there. Seems like the Listeners doesn't work in the MultiBlocProvider what makes sense now when i think of it.

    MultiBlocProvider(
          providers: [
            // All my Providers
          ],
          child: MultiBlocListener(
            listeners: [
              // All my Listeners
            ],
            child: const MaterialApp(
              home: PlayerOverview(),
            ),
          ),
        );