【问题标题】:what is the right way to provide a bloc?提供集团的正确方法是什么?
【发布时间】:2020-08-09 15:25:43
【问题描述】:

大家好,我是 Flutter 的新手,我的问题是提供集团的正确方法是什么? 我决定在命名 rout 部分的主文件中提供主题,但问题是当我需要在其他 bloc 中的 bloc 时我无法提供它。 这是我的主要文件路径部分问题是例如我想向assetPage bloc提供一个AssetDevicesPageBloc bloc我怎么能做这样的事情因为我没有访问权限。我是不是以错误的方式提供集团?我第一次想在一个地方提供所有块然后为每个小部件使用 blockprovider.value 但是当我搜索它时,我发现它使用资源的方式错误。请帮助。谢谢

 return MaterialApp(
  routes: {
    'loginPage': (context) => BlocProvider(
          child: LogInPage(),
          create: (BuildContext context) {
            return LoginBloc(
                userRepository: userRepository,
                authenticationBloc:
                    BlocProvider.of<AuthenticationBloc>(context));
          },
        ),
    'AssetDevicePage': (context) => MultiBlocProvider(
          child: AssetDevicesPage(),
          providers: [
            BlocProvider(
                create: (BuildContext context) => AssetDevicesPageBloc(
                    userRepository: userRepository,
                    dataBaseRepository: dataBaseRepository,
                    deviceRepository: deviceRepository)),
            BlocProvider(
                create: (BuildContext context) => DeviceViewSwitcherBloc(
                    dataBaseRepository, userRepository, deviceRepository)),
            BlocProvider(
                create: (BuildContext context) =>
                    LampBloc(deviceRepository, dataBaseRepository)),
          ],
        ),

    'AssetPage': (context) => MultiBlocProvider(
          providers: [
            BlocProvider(
              create: (BuildContext context) =>
                  CategoryBloc(userRepository, dataBaseRepository),
            ),
            BlocProvider(
              create: (BuildContext context) =>
                  AssetPageBloc(BlocProvider.of<CategoryBloc>(context)),
            ),
          ],
          child: AssetPage(),
        ),

  },

【问题讨论】:

    标签: flutter bloc flutter-bloc


    【解决方案1】:

    问题正在发生,因为该集团在您调用它的上下文中不可用。

    您需要在 materialApp 小部件上方的第一个小部件中初始化 AssetDevicesPageBloc。

    例如在 MyApp Widget 中创建 AssetDevicesPageBloc 的实例。

    AssetDevicesPageBloc assetDevicePageBloc = AssetDevicesPageBloc(
    userRepository: userRepository,
    dataBaseRepository: dataBaseRepository,
    deviceRepository: deviceRepository)
    );
    

    比使用 BlocProvider.value 包装 MaterialApp 小部件并像这样提供创建的块:

    BlocProvider.value(
      value: assetDevicePageBloc,
      child: MaterialApp(),
    );
    

    现在您可以使用以下命令在任何屏幕内的任何位置访问您的块:

    BlocProvider.of< AssetDevicesPageBloc >(context)
    

    但是请记住,如果您初始化 bloc,您应该在初始化它的小部件的 dispose 方法中关闭它的实例。所以调用

    assetDevicePageBloc?.close();
    

    在您初始化assetDevicePageBloc的小部件的dispose方法中。

    参考见official documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多