Syncing providers managing the "same" entity #3712
-
Hey there 👋 TLDR; I have a list and a detail provider of the "same" entity holding some shared state, when updating that shared state who is resposible for the API Call? I am developing an Fleet and Warehouse Management System in Flutter using Riverpod and Supabase. In my database I have the following entities: I want to display an overview about the current fleet in my flutter app and thus created a database view called current_fleet which aggregates all cars and checks if there is any existing car reservation where the current time is in the reservation ("there is an active reservation at this given time"). To prevent overfetching this table only has some data about the car but not all. Since there is also a detail view of each car, which contains more information about a car, I have a CarDetailsProvider which fetches all the information about the car to display it. I now want the user to be able to update the e.g. plate from either the detail view or the overview. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can just call your api in your buttons and then call In any case, where you place the update API call is not really important regarding riverpod I guess. You can also have class CarManager where you put your update methods, which perform the update API call and then the provider updates. @Riverpod(keepAlive: true)
CarManager carManager(CarManagerRef ref) => CarManager(ref);
class CarManager {
final Ref _ref;
const CarManager(this._ref);
Future<void> updatePlate(car, plate) async {
await _ref.read(apiProvider).updatePlate(car, plate);
if (_ref.exists(listProvider)) {
_ref.read(listProvider.notifier).updatePlate(car, plate);
}
if (_ref.exists(detailProvider)) {
_ref.read(detailProvider.notifier).updatePlate(car, plate);
}
}
} |
Beta Was this translation helpful? Give feedback.
You can just call your api in your buttons and then call
ref.invalidate(listProvider)
and same for detailProvider.But it's costly as the providers will be rebuilt. You can instead have an updatePlate() method in both providers, in which you update the provider state directly. You should probably check if ref.exists(provider) before trying to call these methods.
In any case, where you place the update API call is not really important regarding riverpod I guess.
You can also have class CarManager where you put your update methods, which perform the update API call and then the provider updates.