D
State ManagementEasy20 XP4 min read

How does the Provider package work in Flutter?

TL;DR: Provider wraps InheritedWidget around ChangeNotifier models. Widgets read models with context.watch() (rebuilds on change) or context.read() (no rebuild). Notifying listeners is done via notifyListeners().

Full Answer

Provider is the official Flutter-recommended state management package for small-to-medium apps. It uses ChangeNotifier as the state container.

  • ChangeNotifierProvider — provides a ChangeNotifier to the widget tree
  • context.watch<T>() — subscribes; rebuilds widget when T changes
  • context.read<T>() — reads without subscribing; use in callbacks
  • context.select<T, R>((t) => t.field) — rebuilds only when field changes
  • Consumer<T> — widget-level scoped listen; good for partial rebuilds
  • MultiProvider — provides multiple models in one place
🎯

Never call context.watch() inside a callback or initState — it must be called in build(). Use context.read() for event handlers to avoid accidental subscriptions.

Code Examples

dartProvider counter example
Output
Text updates to 'Count: 1', 'Count: 2', etc. on each FAB tap

Common Mistakes

  • Using context.watch() inside a button's onPressed — causes 'called during build' error
  • Creating the provider below the consuming widget in the tree

Interview Tip

💡

Explain context.watch() vs context.read() — this is the #1 Provider question. read() in callbacks, watch() in build().

#Provider#ChangeNotifier#Consumer#context.watch