Flutter-Riverpod - 如何组合提供者以在 Stream 上进行过滤

Flutter-Riverpod - how to combine providers to filter on a Stream

我正在尝试遵循有关如何使用 Flutter 和 Riverpod 组合提供程序来过滤项目列表的示例文档。数据来自使用 Streams 的 Firestore:

final carListProvider = StreamProvider.autoDispose<List<Car>>((ref) {
  final carsRepo = ref.watch(carsRepositoryProvider);
  return carsRepo.cars();
});

一切正常,我可以毫无问题地渲染汽车列表。现在我想为用户提供根据颜色过滤列表的选项:

enum CarColorFilter {
  all,
  red,
  white,
  black,
}

final carListFilter = StateProvider((_) => CarListFilter.all);

然后按照文档示例,我尝试组合提供程序:

final filteredCars = StreamProvider<List<Car>>((ref) {
  final filter = ref.watch(carListFilter);
  final cars = ref.watch(carListProvider); <-- This line throws the error

  switch (filter.state) {
    case CarColorFilter.all:
      return cars;
    case CarColorFilter.red:
      return cars.where(...)

    default:
  }
})

在声明 'cars' 变量的行上,编辑抱怨说:

The argument type 'AutoDisposeStreamProvider<List>' can't be assigned to the parameter type 'AlwaysAliveProviderBase<Object, dynamic>'

我认为我的用例和文档之间的区别在于,在给定的示例中 List<Todo>StateNotifierProvider 而在我的例子中 List<Car>StreamProvider.任何帮助将不胜感激。

在文档中找到答案,张贴在这里以防对其他人有帮助:

When using .autoDispose, you may find yourself in a situation where your application does not compile with an error similar to:

The argument type 'AutoDisposeProvider' can't be assigned to the parameter type 'AlwaysAliveProviderBase'

Don't worry! This error is voluntary. It happens because you most likely have a bug:

You tried to listen to a provider marked with .autoDispose in a provider that is not marked with .autoDispose

将 filteredList 提供程序标记为 autoDispose 可解决问题。