I have a provider like this
@riverpod
class MainProductNew extends _$MainProductNew {
@override
AsyncValue<MainProductStateModel> build(String id) {
return const AsyncValue.loading();
}
Future<void> getMainProduct() async {
final result = await ref.watch(productViewNewRepositoryProvider).getMainProduct(id);
state = AsyncValue.data( state.value!.copyWith(mainProductModel: result.extractDataOrThrow));
}
}
now In my widget I want to listen to changes for mainProductModel. SO I am using select method.
var mainProductState = ref.watch(
MainProductNewProvider(widget.mainProductId)
.select((value) => value.value?.mainProductModel));
in this scenario I will lost when feature to show loading and error, How can I use select without loasing asyncValue feature ?
I want to use a model as a state and inside this model I have a few models, I want to use it in a few widgets, and these widgets will listen to related models when they are changed the widgets will be rebuilt
>Solution :
You can use whenData:
var mainProductState = ref.watch(
MainProductNewProvider(widget.mainProductId)
.select((value) => value.whenData((value) => value.mainProductModel)));
From the documentation:
Shorthand for when to handle only the data case.
For loading/error cases, creates a new AsyncValue with the corresponding generic type while preserving the error/stacktrace.