Back to results for “Dependency Injection”
Flutter › State Management with Provider

How does ProxyProvider let you properly create a given provider whose own value genuinely depends on the current value of a completely separate other already existing provider?

Intermediate

Answer

ProxyProvider lets you properly build a given provider's own value based directly on one or more other separate providers that already genuinely exist further up within the widget tree, automatically and properly recreating that particular dependent value whenever any one of those specific separate upstream providers it genuinely depends on happens to actually change, which is especially useful for a scenario like a genuine ApiClient that needs to be properly reconstructed whenever a separate AuthProvider's own current authentication token actually changes, ensuring that ApiClient always genuinely uses the exact correct, most current up to date token.
ProxyProvider<AuthModel, ApiClient>(
  update: (context, auth, previousApiClient) => ApiClient(token: auth.token),
)
Real-world example An app properly reconstructs its shared ApiClient using ProxyProvider whenever a separate AuthModel's own current token value actually changes, correctly ensuring every single subsequent API call consistently uses the exact correct, most current up to date authentication token.

Common follow-ups: What genuinely happens to the previous ApiClient instance once ProxyProvider properly creates a genuinely new updated one?;How many genuinely separate distinct provider dependencies can a single given ProxyProvider actually genuinely depend on together at once?