Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use asyncValue feature when I am using select

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading