Provider can make a dependency available to a widget subtree and coordinate its lifecycle. Start with a clear model rather than putting business behavior into provider lookup expressions.
Add the package and define ownership
Run flutter pub add provider and import package:provider/provider.dart in the relevant file. The fragment assumes FocusModel extends ChangeNotifier and exposes sessions and finishSession as in the shared-state lesson.
Watch for rendering, read for actions
Watching registers a dependency. Reading obtains the object without asking the current widget to rebuild when it changes. Use the distinction to make the relationship clear.
Worked example
This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.
ChangeNotifierProvider(
create: (_) => FocusModel(),
child: Builder(builder: (context) => Column(children: [
Text('${context.watch<FocusModel>().sessions} completed'),
FilledButton(onPressed: () => context.read<FocusModel>().finishSession(),
child: const Text('Finish session')),
])),
)
Read the result
The provider creates this model and owns its disposal. The Builder is below the provider, so its context can find it. Do not use a create callback to claim ownership of an existing externally owned instance without understanding the lifecycle contract.
Read ownership and reactivity separately
The create callback constructs the model for this scope. A consumer that watches the model registers a relationship needed for rendering. The event callback reads the model to invoke an operation; it does not need to subscribe to every future value merely to handle this one tap.
Moving a provider higher changes the model’s lifetime and who can access it. That may solve a missing-scope error, but it can also keep data alive much longer than the feature needs. Choose the narrowest useful scope rather than placing every provider at the application root.
First reproduce the behavior with the plain notifier example . Then use Provider to deliver that model without changing its business meaning. This isolates the delivery problem from the state-design problem.
Practice and verification
Extract the count into its own consumer widget. Trigger an update and inspect which part rebuilds. Compare watch with select when a model contains several unrelated values.