带有ProxyProvider错误的Flutter Bloc:尝试将Provider与子类型的Listenable / Stream

时间:2020-06-30 13:06:38

标签: flutter bloc flutter-provider

我正在尝试为我的应用提供Bloc,该Bloc依赖于另一项服务。在该Bloc内部,我正在侦听来自注入服务的流。引发此错误:

Tried to use Provider with a subtype of Listenable/Stream (UserBloc).


- ListenableProvider
- ChangeNotifierProvider
- ValueListenableProvider
- StreamProvider

Alternatively, if you are making your own provider, consider using InheritedProvider.
...

这是我的提供商的代码,还有更多,但是这些都导致了问题:

MultiProvider(
  providers: [
    Provider<AuthService>(create: authServiceBuilder),
    ProxyProvider<AuthService, DatabaseService>(
      update: (_, authService, __) => databaseBuilder(_, authService),
    ),
    ProxyProvider<DatabaseService, UserBloc>(
      create: (_) => UserBloc(),
      update: (_, database, bloc) => bloc..updateDependencies(database),
      dispose: (_, bloc) => bloc.close(),
    ),
    ProxyProvider<UserBloc, ProfileBloc>(
      create: (_) => ProfileBloc(),
      update: (_, userBloc, bloc) => bloc..updateDependencies(userBloc),
      dispose: (_, bloc) => bloc.close(),
    ),
  ]
)

集团正在抛出错误,其他服务正常运行。

我尝试在ProxyProvider的update参数中创建Bloc,类似于上面的DatabaseService ProxyProvider,但这是行不通的。

然后执行该操作,以便在create参数中创建Bloc,并且在调用update时,我取消订阅任何流并重新订阅,然后在dispose上调用Blocs close()方法。但这显示了相同的错误。

这大致就是我的UserBloc的样子:

class UserBloc extends Bloc<UserEvent, UserState> {
  DatabaseService _database;

  /// The UI will always reflect this local cache.
  final _userCache = BehaviorSubject<User>();

  StreamSubscription<User> _userSub;
  StreamSubscription<User> _userCacheSub;

  UserBloc() {
    // When the cache updates, update the UI immediately.
    _userCacheSub = _userCache.listen((user) => add(UserUpdated(user)));
  }

  void updateDependencies(DatabaseService database) {
    // Store a new reference to the database.
    _database = database;

    // Cancel existing subscriptions
    if (_userSub != null) _userSub.cancel();

    // Database is always the source of truth. Push upates straight to the cache
    _userSub = _database.userStream.listen((user) => _userCache.add(user));
  }

  @override
  Future<void> close() {
    _userSub.cancel();
    _userCacheSub.cancel();
    return super.close();
  }
}

拥有Bloc到Bloc依赖性的最佳方法是什么?我是否必须将它们放在使用者的下方并在下面提供?还是有办法使其与ProxyProvider一起使用?

0 个答案:

没有答案