import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final counterProvider = StateProvider<int>((ref) => 0);
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: CounterScreen(),
);
}
}
class CounterScreen extends ConsumerWidget {
const CounterScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(title: const Text('Counter App')),
body: Center(
child: Text(
'$counter',
style: const TextStyle(fontSize: 48),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
ref.read(counterProvider.notifier).state++;
},
child: const Icon(Icons.add),
),
);
}
}This app uses Riverpod to manage the counter state simply and clearly.
We create a StateProvider<int> called counterProvider that holds the current count.
Inside CounterScreen, which is a ConsumerWidget, we use ref.watch(counterProvider) to get the current count and rebuild the UI when it changes.
The counter value is shown in a large text in the center.
The floating action button increments the counter by accessing the provider's notifier and increasing its state.
This shows how Riverpod helps keep state management clean and reactive.