在同一个项目中同时使用Bloc和Provider可以吗?

问题描述 投票:0回答:1

假设我在数据库中存储了一些数据,并且我想在启动应用程序时获取这些数据。我还希望可以从我的应用程序上的任何位置访问这些数据,因为我的区块将依赖于它。

因此,我想到使用 Provider 使获取的数据在所有应用程序中可用,并使用 Bloc 来处理我的应用程序中发生的状态或事件,因为据我所知,bloc 不适合像提供者一样简单地将数据放在任何地方都可以访问。

所以我的问题:在应用程序中针对此特定用例同时使用 Provider 和 Bloc 是否可以(Provider 不会用于状态管理,仅用于让数据可以在任何地方访问)?

我问这个问题是因为我看到很多人说我们应该将自己限制在 1 个状态管理包,但正如我所说,这里的提供者并不是作为一种状态管理技术而被用户使用。

flutter state bloc provider state-management
1个回答
0
投票

您不需要额外的提供商即可在应用程序中提供数据。你只需要顶级集团。此外,如果您深入研究 BlocProvider 类,您会注意到 bloc 使用提供程序从上下文访问它:

/// Method that allows widgets to access a [Bloc] or [Cubit] instance
  /// as long as their `BuildContext` contains a [BlocProvider] instance.
  ///
  /// If we want to access an instance of `BlocA` which was provided higher up
  /// in the widget tree we can do so via:
  ///
  /// ```dart
  /// BlocProvider.of<BlocA>(context);
  /// ```
  static T of<T extends StateStreamableSource<Object?>>(
    BuildContext context, {
    bool listen = false,
  }) {
    try {
      return Provider.of<T>(context, listen: listen);
    } on ProviderNotFoundException catch (e) {
      if (e.valueType != T) rethrow;
      throw FlutterError(
        '''
        BlocProvider.of() called with a context that does not contain a $T.
        No ancestor could be found starting from the context that was passed to BlocProvider.of<$T>().

        This can happen if the context you used comes from a widget above the BlocProvider.

        The context used was: $context
        ''',
      );
    }
  }

因此,您绝对可以创建一个顶级块来获取您的数据并在整个应用程序中可用。

© www.soinside.com 2019 - 2024. All rights reserved.