简体   繁体   English

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

[英]Flutter-Riverpod - how to combine providers to filter on a Stream

I'm trying to follow the example docs on how to combine Providers using Flutter & Riverpod to filter a list of items.我正在尝试遵循示例文档,了解如何使用 Flutter 和 Riverpod 组合提供者来过滤项目列表。 The data is coming from Firestore using Streams:数据来自使用 Streams 的 Firestore:

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

This all works fine and I can render the list of cars no problem.这一切都很好,我可以毫无问题地呈现汽车列表。 Now I want to give the user the option to filter the list based on color:现在我想为用户提供基于颜色过滤列表的选项:

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

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

And then following the docs example, my attempt to combine the providers:然后按照文档示例,我尝试合并提供者:

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:
  }
})

On the line declaring the 'cars' variable the editor complains:在声明“汽车”变量的那一行,编辑抱怨:

The argument type 'AutoDisposeStreamProvider<List>' can't be assigned to the parameter type 'AlwaysAliveProviderBase<Object, dynamic>'参数类型“AutoDisposeStreamProvider<List>”不能分配给参数类型“AlwaysAliveProviderBase<Object, dynamic>”

I think the difference between my use case and the docs is that in the example given the List<Todo> is a StateNotifierProvider whereas in my case the List<Car> is a StreamProvider .我认为我的用例和文档之间的区别在于,在给出的示例中List<Todo>StateNotifierProvider而在我的情况下List<Car>StreamProvider Any help would be much appreciated.任何帮助将非常感激。

Found the answer in the docs, posting here in case it helps anyone else:在文档中找到答案,在此处发布以防对其他人有帮助:

When using.autoDispose, you may find yourself in a situation where your application does not compile with an error similar to:使用.autoDispose 时,您可能会发现自己的应用程序无法编译并出现类似以下错误:

The argument type 'AutoDisposeProvider' can't be assigned to the parameter type 'AlwaysAliveProviderBase'参数类型“AutoDisposeProvider”不能分配给参数类型“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您尝试在未标记为 .autoDispose 的提供程序中侦听标记为 .autoDispose 的提供程序

Marking the filteredList provider as autoDispose resolves the issue.将过滤列表提供程序标记为autoDispose可以解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM