【问题标题】:Is there anyway that I can use MultiBlocProvider to clean this nest of widgets up?无论如何,我可以使用 MultiBlocProvider 来清理这个小部件巢吗?
【发布时间】:2020-08-06 01:18:39
【问题描述】:

我正在尝试清理这些杂乱无章的小部件,但我没有办法这样做。我的NavigationBloc 依赖于AuthenticationBloc 提供的流,为了防止内存泄漏,我必须关闭流。

需要 Builder 小部件,以便我可以获得BlocProvider 提供的最新BuildContext,但我知道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: '/'),
          ),
        );
      }),
    );
  }
}

【问题讨论】:

  • 为什么你确定有更好的方法?

标签: flutter bloc flutter-bloc


【解决方案1】:

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

你必须在initState()方法中创建你的AuthenticationBloc

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2020-07-03
    • 2012-09-21
    • 2015-01-04
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多