Flutter-Riverpod -如何在流上组合提供商进行过滤



我试图遵循如何使用Flutter组合提供商的示例文档;Riverpod来过滤项目列表。数据来自Firestore使用Streams:

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

这一切都很好,我可以渲染汽车列表没有问题。现在我想给用户一个选项来根据color:

筛选列表
enum CarColorFilter {
all,
red,
white,
black,
}
final carListFilter = StateProvider((_) => CarListFilter.all);

然后按照docs的例子,我尝试组合提供程序:

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'变量的那行,编辑器报错了:

参数类型'AutoDisposeStreamProvider'不能是分配给参数类型'AlwaysAliveProviderBase<Object,dynamic> '

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

在文档中找到了答案,在这里发布,以防它对其他人有所帮助:

在使用.autoDispose时,您可能会发现自己处于这样的情况应用程序编译时没有出现类似以下错误:

参数类型'AutoDisposeProvider'不能分配给参数类型'AlwaysAliveProviderBase'

别担心!这个错误是自愿的。它的发生是因为你最可能有错误:

你试图监听一个带有。autodispose标记的提供者未标记为.autoDispose

的提供程序

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

最新更新