Flutter Provider - Circular Dependencies using ProxyProvider`

1,584

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.

Share:
1,584
Eliya Cohen
Author by

Eliya Cohen

Updated on December 12, 2022

Comments

  • Eliya Cohen
    Eliya Cohen over 1 year

    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.