agriz
agriz

Reputation: 759

Flutter - Is it possible to use BLoC without provider?

class App extends StatefulWidget {
....
return HomeProvider(
   homeBloc: HomeBloc(),
   child: MaterialApp(
      home: HomeScreen(),
   ),
);

class HomeScreen extends StatefulWidget {
   HomeBloc homeBloc = HomeBloc();
}  

From the above two scenarios, Most of the tutorials I read, is using the first option. Is the second method completely wrong? or does it have any negative effects in-app?

I can see one difference. I can access the homeBloc by HomeProvider.of context in the first method. For the second method, I have to pass homeBloc in all the widgets.

Upvotes: 2

Views: 891

Answers (2)

forJ
forJ

Reputation: 4617

It is definitely possible. I using a single bloc for my entire application right now (as I have come from react-native redux, apollo background, single source of truth makes more sense for me). An example is like below. You can declare your single instance of bloc and import it wherever you use it so you refer to same instance.

class Bloc {
  /// Your Bloc Stuff
}

final bloc = Bloc();

Upvotes: 1

Riven
Riven

Reputation: 796

Sure, you can use bloc without a provider. But if you share 2 screens with the same bloc, the stream value inside the bloc will be different, because you don't use the InheritedWidget (usually in a provider). The function of a provider is to provide your bloc with InhteritedWidget, so that multiple screens could access to the same stream.

Upvotes: 3

Related Questions