Eliya Cohen
Eliya Cohen

Reputation: 11508

Flutter Provider - Circular Dependencies using ProxyProvider`

I have the following services:

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

Which lead me to write:

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),
  ),
],

I can tell until this point that it already looks messy. But that's not the case. When I run the app, I get the following error:

enter image description here

So what I do? I add before all of the ProxyProviders a Provider<AuthService>. But then, the AuthService is being constructed twice! Which loses the whole point of being a singular instance (or isn't it?).

My main goal is to make a sort-of dependency injection just like in Angular or Laravel.

Upvotes: 4

Views: 2328

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277597

ProxyProvider and widgets in general fights against circular dependencies, as it's usually a sign of "spaghetti code" (see more)

As such, using ProxyProvider you won't be able to make a circular dependency graph.

If that's truly what you want, consider using Provider.value and manually handling your dependencies.

Upvotes: 5

Related Questions