// import Provider package...
// 1. Model
class CounterNotifier with ChangeNotifier { // Use:--- with ChangeNotifier
int number = 0;
void increase() {
number++;
notifyListeners(); // --- notifyListeners()
}
void decrease() {
number--;
notifyListeners(); // --- notifyListeners()
}
}
// 2. MyApp()
return ChangeNotifierProvider(
create: (context) => CounterNotifier(),
child: const MaterialApp(
home: ChangeNotifierProviderScreen(),
),
);
// 3. ChildScreen()
return Scaffold(
appBar: AppBar(
title: const Text('Next Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: context.read<CounterNotifier>().increase, // Use: context.read<T>().property or method
child: Text(
'+++ ${context.watch<CounterNotifier>().number}', // Use: context.watch<T>().property
style: Theme.of(context).textTheme.headline5,
),
),
ElevatedButton(
onPressed: context.read<CounterNotifier>().decrease, // Use: context.read<T>().property or method
child: Text(
'--- ${context.watch<CounterNotifier>().number}', // Use: context.watch<T>().property
style: Theme.of(context).textTheme.headline5,
),
),
Consumer<CounterNotifier>( // Use: Consumer<T>() Widget
builder: (context, value, child) => Text('${value.number}'),
),
Consumer<CounterNotifier>( // Use: Consumer<T>() Widget
builder: (context, value, child) => ElevatedButton(
onPressed: value.increase,
child: const Text('Increase'),
),
),
Consumer<CounterNotifier>( // Use: Consumer<T>() Widget /
builder: (context, value, child) => ElevatedButton(
onPressed: value.decrease,
child: const Text('Decrease'),
),
),
],
),
),
);