2

我正在尝试清理这些乱七八糟的小部件,但我没有办法这样做。我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: '/'),
          ),
        );
      }),
    );
  }
}
4

1 回答 1

2

正如您所说,您可以使用MultiProvider来避免嵌套提供程序

你必须AuthenticationBlocinitState()方法中创建你的

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: '/'),
          );
        },
      ),
    );
  }
}
于 2020-04-22T22:19:48.067 回答