I know that some of my BLOCs will be instantiated only once throughout the app lifecycle. Is it bad practice or anti-pattern to create these BLOC classes as a singleton. Singleton can help in accessing the BLOC anywhere and also makes sure that the class is instantiated only once.
I can also ensure to be safe when using one BLOC inside another BLOC and passing around the singleton as if it were "just another" implementation.
What might be the effects of doing so?
Edit
I have two Blocs
- AuthenTicationBloc - this is a global bloc
- UserBloc - should exist only once (singleton)
The AuthenTicationBloc has to use the UserBloc inside it. If I made UserBloc a singleton , it would make it easy to just use it as UserBloc()
.
Othewise I had to create UserBloc as an instance variable in AuthenTicationBloc as follows:
class AuthenTicationBloc {
UserBloc _userBloc;
AuthenTicationBloc({@required UserBloc userBloc}) : _userBloc = userBloc;
myMethod(){
//use the userBloc
_userBloc.setDetails();
}
}
runApp(
UserBloc userBloc = UserBloc();
Provider(
value: AuthenTicationBloc(userBloc: userBloc),
child: MyApp(),
),
);
If I had to use the UserBloc down the widgetchain somewhere else I had to make the UserBloc also be provided globally as follows right?
UserBloc userBloc = UserBloc();
MultiProvider(
providers: [
Provider<AuthenTicationBloc>(
value: AuthenTicationBloc(userBloc:userBloc),
),
Provider<UserBloc>(
value: userBloc,
),
],
child: MyApp(),
);