What is the difference between using context.watch<Counter>().count from the example on the Provider package page and using a Consumer widget when trying to use the provider values?
Using context.watch().count to get the current value:
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<Counter>().count}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headlineMedium,
);
}
}
Using a Consumer widget:
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Consumer<Counter>(
builder: (context, value, child) {
return Text(value.count);
}
);
}
}
Counter class:
class Counter with ChangeNotifier, DiagnosticableTreeMixin {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
/// Makes `Counter` readable inside the devtools by listing all of its properties
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('count', count));
}
}
Effectively nothing.
Consumeris doing nothing outside of callingcontext.watchand sending that tobuilder.The main reason
Consumerexists is:Stateless/StatefulWidget.BuildContextlikely wouldn't have access to the Provider. UsingConsumersolves this problem as it would be under the Provider.