简体   繁体   中英

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. The data is coming from Firestore using Streams:

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>'

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 . 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:

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

Marking the filteredList provider as autoDispose resolves the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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