【问题标题】:What is the advantage of using dependency injection with providers in Flutter's riverpod?在 Flutter 的 riverpod 中使用提供程序依赖注入有什么优势?
【发布时间】:2023-01-22 06:19:03
【问题描述】:

经常看到有人在flutter中为每个类定义依赖时说用riverpod。

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

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

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

但是,我不明白为什么使用 riverpod 是个好主意的好处。 不应该像下面这样在使用的时候初始化吗?

我觉得下面的写法在测试方面已经足够了,比如可以用测试文件来初始化mock。


final githubRepository = GithubRepositoryImpl(GithubApiClientImpl());

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

为什么要费心使用 riverpod?

【问题讨论】:

    标签: flutter riverpod


    【解决方案1】:

    1 - 没有任何东西是开箱即用的,它是在第一次有人请求它时被初始化的,例如ref.read(fooProvider)

    文档: 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 - 对于模拟,您可以覆盖提供者,请参阅文档以获取更多信息

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

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多