3

I often see people talking about using riverpod when defining dependencies for each class in flutter.

final apiClientProvider = Provider.autoDispose(
  (_) => GithubApiClientImpl(),
);

final githubRepositoryProvider = Provider.autoDispose(
  (ref) => GithubRepositoryImpl(ref.read(apiClientProvider)),
);

final repositoryListViewModelProvider = StateNotifierProvider.autoDispose(
  (ref) => RepositoryListViewModel(ref.read(githubRepositoryProvider)),
);

However, I do not understand the benefits of why it is a good idea to use riverpod. Shouldn't it be initialized at the time of use as shown below?

I feel that the following writing style is sufficient in terms of testing, for example, you can initialize the mock with a test file.


final githubRepository = GithubRepositoryImpl(GithubApiClientImpl());

final repositoryListViewModel = RepositoryListViewModel(GithubRepositoryImpl(GithubApiClientImpl()));

Why bother using riverpod?

Progman
  • 16,827
  • 6
  • 33
  • 48
hime_chann____
  • 141
  • 1
  • 5

1 Answers1

0

1 - there is nothing that gets initialized out of the box it get initialized first time someone request it for example ref.read(fooProvider)

the docs: https://docs-v2.riverpod.dev/docs/concepts/providers#creating-a-provider

Do not be frightened by the global aspect of providers. Providers are fully immutable. Declaring a provider is no different from declaring a function, and providers are testable and maintainable.

2 - for mocking you can override a provider see the docs for more info

https://docs-v2.riverpod.dev/docs/cookbooks/testing#overriding-the-behavior-of-a-provider-during-tests

Ahmed Masoud
  • 309
  • 3
  • 8