Search code examples
flutterriverpod

flutter riverpod: initialize state on notify provider


I am using notifier 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));
  }
}

When I am calling getMainProduct method and I want to update the state , since state value is null I get :

Error: Unexpected null value.

the issue is here :

state.value!.copyWith

MainProductStateModel is a freezed class, How can I correctly initialize the state?

Do I need to create an object if the state is null but after that I can use copywith, Is it correct ?


Solution

  • In general, if your state shoudl be AsyncLoading until a known future completes, return that future. So your code should look like this:

    @riverpod
    class MainProductNew extends _$MainProductNew {
      @override
      Future<MainProductStateModel> build(String id) {
        return _getMainProduct();
      }
    
      Future<MainProductStateModel> _getMainProduct() async {
        final result = await ref.watch(productViewNewRepositoryProvider).getMainProduct(id);
    
        return result;
      }
    }
    

    I made it private to distinguish between internal functions and external mutation API methods. And you could further simplify that internal function as:

      Future<MainProductStateModel> _getMainProduct() =>
        ref.watch(productViewNewRepositoryProvider).getMainProduct(id);