无论如何,我可以使用MultiBlocProvider清理此嵌套的窗口小部件吗?

时间:2020-04-22 20:55:54

标签: flutter bloc flutter-bloc

我正在尝试清理这些混乱的小部件,但我发现没有办法。我的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: '/'),
          ),
        );
      }),
    );
  }
}

1 个答案:

答案 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: '/'),
          );
        },
      ),
    );
  }
}