Search code examples
flutterdartblocprovider

ProviderNotFoundException in flutter app with Bloc


I want to create an app containing a few screens where a user have a possibility to choose different options. On the last screen I have a checking if the object already exists in the database with bloc. However, I am constantly getting this error: screenshot of the error. It only happens with this part of the app, in the others everything works perfectly. I navigate between screens by Navigator.pushNamed and app router, which is initialized inside main file. This is the main file itself:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await di.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    DateTime max_date =
        DateTime(DateTime.now().year, (DateTime.now().month + 1) % 13, 0);
    return MultiBlocProvider(
      providers: [
        BlocProvider<MoodBloc>(
            create: (context) => di.sl<MoodBloc>()
              ..add(LoadMoodsEvent(
                  max_date: max_date, days_amount: max_date.day))),
      ],
      child: MaterialApp(
        theme: theme(),
        debugShowCheckedModeBanner: false,
        //home: ChooseMoodPage(),
        onGenerateRoute: AppRouter.onGenerateRoute,
        initialRoute: HomePage.routeName,
      ),
    );
  }
}

This is the part of code, which causes the error:

Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          BlocListener(
            listener: (context, state) {
              if (state is MoodStoreLoaded) {
                BlocProvider.of<MoodBloc>(context).add(
                    LoadMoodsEvent(max_date: DateTime.now(), days_amount: 30));
                Navigator.pushReplacementNamed(context, '/');
              } else if (state is MoodDeletedByDate) {
                BlocProvider.of<MoodBloc>(context).add(
                  StoreMoodEvent(
                    mood: MoodEntity(
                      username: 'user1',
                      date: widget.args.max_date!,
                      value: widget.args.mood!,
                      sphere: widget.args.sphere,
                      heading: widget.args.heading,
                      note: widget.args.note,
                      photos: convert_photo_list_to_string(
                          widget.args.photos ?? []),
                    ),
                  ),
                );
              }
            },
  

It's written everywhere, that the problem is about the parent widgets and provider relation, but I have initialized everything inside the head parent of my app.


Solution

  • Add BlocListener with <MoodBloc, MoodState> like BlocListener<MoodBloc, MoodState>.

    P.S. I supposed MoodState is the state of your MoodBloc