Replace runApp with
void main() {
runApp(const ProviderScope(child: MyApp()));
}
// Provider is used to access immutable objects
final counter = Provider<int>((ref) {
return 1;
});
// StateProvider is used to access simple mutable object
final counter2 = StateProvider<int>((ref) {
return 100;
});
// StateNotifierProvider is used to access complex mutable objects
final counter3 = StateNotifierProvider<MyCounterProvider, int>((ref) {
return MyCounterProvider();
});
class HomePage extends ConsumerWidget {
...
...
Widget build(BuildContext context, WidgetRef ref) {
...
...
final counterData = ref.watch(counter);
...
...
Text(
'$counterData',
...
...)
}
}
Consumer(
builder: (context, ref, child) {
final counterData = ref.watch(counter);
return Text(
'$counterData',
style: Theme.of(context).textTheme.headlineMedium,
);
},
),
class HomePage3 extends ConsumerStatefulWidget {
ConsumerState<HomePage3> createState() => _HomePage3State();
class _HomePage3State extends ConsumerState<HomePage3> {
// Inside build
final counterData = ref.watch(counter);
...
...
Text('$counterData');
...
// Inside init state
// Here we used 'read' not 'watch'
final counterData = ref.read(counter);
// Updating data if using 'StateProvider'
ref.read(counter2.notifier).state++;
// or
ref.read(counter2.notifier).update((state) {
return state + 1;
});
// or
ref.read(counter2.notifier).update((state) => state + 1);
// To reset the sate
ref.invalidate(counter2);
// or
ref.refresh(counter2);
...
// Listen the changes (Inside build)
ref.listen(
counter2,
(previous, next) {
log('Previous: $previous');
log('Next: $next');
},
);
ref.watch() => Observe the state inside build method to update the widgets ref.read() => To read the state onece
// If we use StateNotifierProvider
// StateNotifierProvider is used to access complex mutable objects
final counter3 = StateNotifierProvider<MyCounterProvider, int>((ref) {
return MyCounterProvider();
});
// Our class
class MyCounterProvider extends StateNotifier<int> {
// 248 as initial value
MyCounterProvider() : super(248);
void incrementCounter() {
state++;
}
}
// How to access data
final counterData3 = ref.watch(counter3);
// How to access functions
ref.read(counter3.notifier).incrementCounter();