我正在尝试清理这些混乱的小部件,但我发现没有办法。我的NavigationBloc
取决于AuthenticationBloc
提供的流,为了防止内存泄漏,我必须关闭该流。
需要Builder窗口小部件,这样我才能获得BuildContext
提供的最新BlocProvider
,但我知道MultiBlocProvider
可以极大地清除此问题。我想避免将此小部件包装在runApp
函数中,但是我猜这是一个选择。
class _MyAppState extends State<MyApp> {
final authRepo = AuthRepo();
AuthenticationBloc authBloc;
@override
void dispose() {
authBloc?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider<AuthenticationBloc>(
create: (_) =>
AuthenticationBloc(authRepo: authRepo)..add(InitializeAuth()),
child: Builder(builder: (context) {
authBloc = context.bloc<AuthenticationBloc>();
return BlocProvider<NavigationBloc>(
create: (_) => NavigationBloc(authBloc),
child: MaterialApp(
title: 'Arrow Manager',
debugShowCheckedModeBanner: false,
theme: appTheme(),
builder:
ExtendedNavigator<Router>(router: Router(), initialRoute: '/'),
),
);
}),
);
}
}
答案 0 :(得分:2)
正如您所说,您可以使用MultiProvider
来避免嵌套提供程序
您必须使用AuthenticationBloc
方法创建initState()
class _MyAppState extends State<MyApp> {
final authRepo = AuthRepo();
AuthenticationBloc authBloc;
@override
void initState() {
super.initState();
authBloc = AuthenticationBloc(authRepo: authRepo);
}
@override
void dispose() {
authBloc?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (_) => authBloc..add(InitializeAuth()),
),
BlocProvider(
create: (context) => NavigationBloc(authBloc),
),
],
child: Builder(
builder: (context) {
authBloc = context.bloc<AuthenticationBloc>();
return MaterialApp(
title: 'Arrow Manager',
debugShowCheckedModeBanner: false,
theme: appTheme(),
builder: ExtendedNavigator<Router>(router: Router(), initialRoute: '/'),
);
},
),
);
}
}