import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Counter(),
child: const MaterialApp(
home: CounterScreen(),
),
);
}
}
class Counter extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class CounterScreen extends StatelessWidget {
const CounterScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter with State')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Count:'),
Consumer<Counter>(
builder: (context, counter, child) {
return Text(
'${counter.count}',
style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
);
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
context.read<Counter>().increment();
},
child: const Text('Increment +'),
),
],
),
),
);
}
}
We created a Counter class that extends ChangeNotifier. It holds a private integer _count and a getter count. The increment() method increases _count by 1 and calls notifyListeners() to tell widgets to update.
In MyApp, we use ChangeNotifierProvider to provide the Counter instance to the widget tree.
In CounterScreen, we use a Consumer<Counter> widget to listen for changes and rebuild the Text widget showing the current count.
The button calls context.read<Counter>().increment() to update the count.
This setup keeps state management clean and UI reactive without manual setState calls.