'How to have single instance of a bloc across other blocs
How can I avoid creating another instance of some bloc class?
I have two blocs: LoginBloc
and AuthBloc
. and LoginBloc accepts an instance of AuthBLoc and here is problem:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final UserRepository repository=UserRepository();
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => LoginBloc(
//******Extra Instance of AuthBloc in being created here because LoginBloc needs it to listen********
authBloc: AuthBloc(SInitialState(),userRepository: repository), userRepository:repository
),
),
BlocProvider(
create: (context) => AuthBloc(SInitialState(),userRepository: repository),
)
],
child: MaterialApp(...);
Thanks in advance.
Solution 1:[1]
You can assign AuthBloc
to a variable inside build()
method.
Or, just nest one BlockProvider
inside another one:
BlocProvider<AuthBloc>(
create: (context) => AuthBloc(SInitialState(),userRepository: repository),
child: BlocBuilder<AuthBloc, AuthState>(
builder: (BuildContext context, AuthState authState) {
return BlocProvider(
create: (context) => LoginBloc(
authBloc: context.bloc<AuthBloc>(),
userRepository: repository,
),
child: MaterialApp(...),
)
})
),
But the best solution is Bloc to Bloc communication
Solution 2:[2]
if I got you question correctly, you might use GetIt and here is a sample code
MultiBlocProvider(
providers: [
BlocProvider<SginInBloc>(
create: (BuildContext context) => sl<SginInBloc>(),
child: SginInPage(),
),....
so that you will get access to the instans of that Bloc that will be created
final sl = GetIt.instance;
sl.registerFactory(() => SginInBloc();
here I'm using registerFactory but you can use registerSingleton depends on what you want to achive
Solution 3:[3]
void main() {
final UserRepository repository=UserRepository();
runApp(MyApp(authBloc: AuthBloc(),userRepo : repository));
}
class MyApp extends StatelessWidget {
final AuthBloc authBloc;
final UserRepository userRepo;
MyApp({required this.authBloc,required this.userRepo});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => LoginBloc(
//******Extra Instance of AuthBloc in being created here because LoginBloc needs it to listen********
authBloc: authBloc,userRepository: userRepo), userRepository:userRepo
),
),
BlocProvider(
create: (context) => authBloc,
)
],
child: MaterialApp(...);
Try this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Owczar |
Solution 2 | |
Solution 3 | Aswanath C K |