Reputation: 941
I have a state provider and a future provider that obtains data from this particular state provider. Let’s call this selectedEntityStateProvider and call future provider as weatherDataFutureProvider.
I have a PageView which user can scroll and when page changed, I update the selectedEntityStateProvider which triggers weatherDataFutureProvider to rebuild itself because it watches the selectedEntityStateProvider.
So I'm expecting at first scroll, it fetches data for new value in selectedEntityStateProvider. But when I scroll back to a previous index, it still fetches the data which already fetched before so it rebuilds itself and cause an extra network request.
Inside of onPageChanged:
ref
.watch(
selectedEntityStateProvider
.notifier)
.update((state) => list[value]);
setState(() {
currentIndex = value;
});
currentIndex is used to display a list of indicator widgets based on which index is selected.
weatherDataFutureProvider is like that:
final weatherDataFutureProvider =
FutureProvider.family<dynamic, int>((ref, value) async {
if (value == 1) {
var selectedEntity = ref.watch(selectedEntityStateProvider);
var weatherService = WeatherService();
var weatherServiceResponse = await weatherService.callService(
lat: selectedEntity!.address.latitude!,
lng: selectedEntity!.address.longitude!,
);
return weatherServiceResponse;
}
Family modifier used for to determine different type of entities. 1 is urban, 2 is rural etc and it is coming from a parent State as a final value.
So, at this step, how can I prevent a future provider rebuilds itself? Or is there a way that I can detect what causing this future provider rebuilds itself and losing previous data?
Upvotes: 0
Views: 56
Reputation: 8519
The idea is, you have to pass the value of selectedEntity
as a family key somehow. Maybe you can consider using a record so that you can pass both selectedEntity
and that type (the one you're currently using as family key) as the new family key, or you can use the new code generation syntax which allows you to have multiple family keys.
Please also note that StateProvider
is no longer recommended *). If the selectedEntity
is only used locally in a widget, consider making a regular state variable in your StatefulWidget
instead, or use useState
from flutter_hooks. If you really need an app-wide state management for your selectedEntity
state, consider making a Notifier.
*) As Riverpod 2.0 introduced Notifier
/AsyncNotifier
, StateNotifier
is now discouraged. That means, the usage of StateNotifierProvider
and StateProvider
(which is a simplification of StateNotifierProvider
) is also discouraged.
Upvotes: 2