如何避免创建某个bloc类的另一个实例?
我有两个集团:AuthBloc
和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(...);
。和LoginBloc接受AuthBLoc的实例,这是问题所在:
{{1}}
谢谢。
答案 0 :(得分:0)
您可以在AuthBloc
方法内将build()
分配给变量。
或者,将一个BlockProvider
嵌套在另一个{1>}中:
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(...),
)
})
),
但是最好的解决方案是Bloc to Bloc communication
答案 1 :(得分:0)
如果我正确提示您问题,则可以使用GetIt 这是示例代码
MultiBlocProvider(
providers: [
BlocProvider<SginInBloc>(
create: (BuildContext context) => sl<SginInBloc>(),
child: SginInPage(),
),....
这样您就可以访问将要创建的Bloc的实例
final sl = GetIt.instance;
sl.registerFactory(() => SginInBloc();
这里我使用的是 registerFactory ,但是您可以使用 registerSingleton 取决于您要达到的目标