Created
May 18, 2024 14:51
-
-
Save sgruhier/02fe00f501569c2483724d6033a0ec06 to your computer and use it in GitHub Desktop.
counter example with riverpod
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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