-
|
This is probably a lame question, but I have to ask it since I only have React/Redux background and Dart is my first OO language. So I have this code in my app that provides weather data based on location and online status. As you can see, I also have a separate loadingStatesProvider (it's a StateNotifier) that controls my circular loading indicator, and I change the state of this provider inside the weatherProvider. But I feel this approach is not 'idiomatic' or 'natural' for Riverpod and Flutter in general. Maybe I have to create a sealed/union class for my weatherProvider state using freezed for example? Please help me clarify the best practices in this regard. I would also be grateful for good sources/references. final weatherProvider =
StreamProvider.autoDispose<CurrentWeather?>((ref) async* {
final isOnlineFuture = ref.watch(onlineStatusProvider.future);
final locationFuture = ref.watch(locationProvider.future);
final loadingStates = ref.watch(loadingStatesProvider.notifier);
CurrentWeather? result;
final isOnline = await isOnlineFuture;
final location = await locationFuture;
if ((isOnline ?? false) && location != null) {
try {
loadingStates.setIsWeatherLoading(true);
final params = {
'lang': '$locale',
'q': '${location.position.latitude},${location.position.longitude}',
};
final data = await client.getCurrentWeather(params);
await persistWeatherData(data);
result = data;
loadingStates.setIsWeatherLoading(false);
} on Exception catch (errorObj, stackTrace) {
result = retrievePersistedWeatherData();
if (errorObj is DioError) {
final res = errorObj.response;
if (res is Response) {
await Sentry.captureMessage(
'Weather fetch response: ${res.data}. Request options: ${res.requestOptions}',
level: SentryLevel.warning,
);
}
} else {
await Sentry.captureException(errorObj, stackTrace: stackTrace);
}
}
} else {
result = retrievePersistedWeatherData();
}
yield result;
});class LoadingStatesModel {
bool isWeatherLoading;
LoadingStatesModel({
bool? isWeatherLoading,
}) : this.isWeatherLoading = isWeatherLoading ?? false;
LoadingStatesModel copyWith({
bool? isWeatherLoading,
}) =>
LoadingStatesModel(
isWeatherLoading: isWeatherLoading ?? this.isWeatherLoading,
);
}
class LoadingStatesNotifier extends StateNotifier<LoadingStatesModel> {
LoadingStatesNotifier() : super(LoadingStatesModel());
void setIsWeatherLoading(bool isWeatherLoading) =>
state = state.copyWith(isWeatherLoading: isWeatherLoading);
}
final loadingStatesProvider =
StateNotifierProvider<LoadingStatesNotifier, LoadingStatesModel>(
(ref) => LoadingStatesNotifier()); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
OK, I figured it out by myself thanks to this awesome tutorial. Freezed sealed classes + StateNotifier rock! |
Beta Was this translation helpful? Give feedback.
OK, I figured it out by myself thanks to this awesome tutorial. Freezed sealed classes + StateNotifier rock!