Search code examples
flutterstateblocproviderstate-management

Is it okay to use both Bloc and Provider in the same project?


Let's assume that I have some data stored in a database and that I wanna fetch that data when launching my app. I also want that data to be accessible from anywhere on my app because my blocs will depend on it.

So I thought of using Provider to make the data fetched available across all the app and Bloc to handle the state or the events occuring in my app because as of my knowledge, bloc isn't suited to simply put data accessible everywhere like provider.

So my question: Is it okay to use both Provider and Bloc in an app for this specific usecase (Provider won't be used for state management, only for letting data be accedsible anywhere) ?

I'm asking this question because I've seen a lot of people saye that we should limit ourselves to 1 state management package but as I said, here provider is not being user as a state management technique.


Solution

  • you don't need additional provider to make data available in the app. you just need top level bloc. moreover, if you dive in to the class BlocProvider you will notice that bloc use provider to access it from context:

    /// Method that allows widgets to access a [Bloc] or [Cubit] instance
      /// as long as their `BuildContext` contains a [BlocProvider] instance.
      ///
      /// If we want to access an instance of `BlocA` which was provided higher up
      /// in the widget tree we can do so via:
      ///
      /// ```dart
      /// BlocProvider.of<BlocA>(context);
      /// ```
      static T of<T extends StateStreamableSource<Object?>>(
        BuildContext context, {
        bool listen = false,
      }) {
        try {
          return Provider.of<T>(context, listen: listen);
        } on ProviderNotFoundException catch (e) {
          if (e.valueType != T) rethrow;
          throw FlutterError(
            '''
            BlocProvider.of() called with a context that does not contain a $T.
            No ancestor could be found starting from the context that was passed to BlocProvider.of<$T>().
    
            This can happen if the context you used comes from a widget above the BlocProvider.
    
            The context used was: $context
            ''',
          );
        }
      }
    

    so, you can definitely make a top level bloc that will fetch your data and be available throughout the application.