Flutter Provider - 使用 ProxyProvider 的循环依赖

标签 flutter dart circular-dependency flutter-provider

我有以下服务:

  1. SecuredStorageService()
  2. ApiService({this.authService})
  3. AuthService({this.securedStorageService, this.apiService})
  4. RegisterService({this.apiService, this.securedStorageService})

这让我写:

providers: [
  Provider<SecuredStorageService>.value(value: SecuredStorageService()),
  ProxyProvider<AuthService, ApiService>(
    builder: (_, auth, __) => ApiService(authService: auth),
  ),
  ProxyProvider2<ApiService, SecuredStorageService, RegisterService>(
    builder: (_, api, storage, __) => RegisterService(apiService: api, securedStorageService: storage),
  ),
  ProxyProvider2<ApiService, SecuredStorageService, AuthService>(
    builder: (_, api, storage, __) => AuthService(apiService: api, securedStorageService: storage),
  ),
],

到目前为止,我可以说它看起来已经很乱了。但事实并非如此。当我运行该应用程序时,出现以下错误:

enter image description here

那我怎么办?我在所有 ProxyProvider 之前添加一个Provider<AuthService> .但是,AuthService 被构造了两次!这失去了作为单一实例的全部意义(或者不是吗?)。

我的主要目标是像在 Angular 或 Laravel 中一样进行某种依赖注入(inject)。

最佳答案

ProxyProvider 和小部件通常与循环依赖作斗争,因为它通常是“意大利面条代码”( see more ) 的标志

因此,使用 ProxyProvider 您将无法制作循环依赖图。

如果这确实是您想要的,请考虑使用 Provider.value 并手动处理您的依赖项。

关于Flutter Provider - 使用 ProxyProvider 的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926028/

相关文章:

paypal - 通过 webview flutter Paypal

flutter - 为 Circle Avatar 小部件 overflow hidden (Flutter)

C++ 循环依赖 : What should the constructor look like?

c++ - 三法则的异常(exception)?

c# - 使用贫血域模型的服务之间的循环引用

android - 错误 : unable to locate asset entry in pubspec. yaml: "assets/fonts/Lato-Regular.ttf"

android - 无法从 api 获取数据,Future 总是返回 null - flutter

dart - 如何从绝对 URL 制作 AngularDart 请求模板?

flutter - SliverList/SliverChildBuilderDelegate 提供初始索引或允许负索引

flutter - 使用提供者值 flutter 初始路线