Skip to content

Instantly share code, notes, and snippets.

@sgruhier
Created May 18, 2024 14:51
Show Gist options
  • Save sgruhier/02fe00f501569c2483724d6033a0ec06 to your computer and use it in GitHub Desktop.
Save sgruhier/02fe00f501569c2483724d6033a0ec06 to your computer and use it in GitHub Desktop.
counter example with riverpod
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// Define the StateProvider for the counter
final counterProvider = StateProvider<int>((ref) => 0);
void main() {
runApp(
ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterPage(),
);
}
}
class CounterPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(title: Text('Counter Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Count: $count', style: TextStyle(fontSize: 24)),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
ref.read(counterProvider.notifier).state++;
},
child: Text('Increment'),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment