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

What is the Provider package, and how does it let you properly share a given piece of state across several separate different widgets without needing to manually pass it down through every single intermediate widget constructor?

Beginner

Answer

Provider is a genuinely popular, officially recommended state management package built directly on top of Flutter's own core InheritedWidget mechanism, letting you properly make a given piece of data or a service instance available to any descendant widget anywhere further down within the widget tree, and any widget can then genuinely access that shared provided data simply by calling Provider.of or using the considerably more convenient context.watch or context.read extension methods, entirely without needing that same particular data to be manually and explicitly passed down individually through every single intermediate widget constructor along the way.
ChangeNotifierProvider(
  create: (context) => CartModel(),
  child: MyApp(),
)

// Elsewhere in the widget tree
final cart = context.watch<CartModel>();
Real-world example A shopping app provides a single shared CartModel instance at the very top of its own widget tree, letting any screen anywhere throughout the entire app freely access and properly update that exact same shared cart data without needing it manually passed down through several genuinely unrelated intermediate widgets.

Common follow-ups: What is the specific practical difference between context.watch and context.read?;What is ChangeNotifier, and how does it genuinely relate to how Provider actually properly works?