Created
February 12, 2022 10:04
-
-
Save wingkit-leung/d28ede90bdb3e8b03812756b9fd9c609 to your computer and use it in GitHub Desktop.
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'; | |
// A Counter example implemented with riverpod | |
void main() { | |
runApp( | |
// Adding ProviderScope enables Riverpod for the entire project | |
const ProviderScope(child: MyApp()), | |
); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp(home: Home()); | |
} | |
} | |
/// Providers are declared globally and specify how to create a state | |
final counterProvider = StateProvider((ref) => 0); | |
class Home extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Counter example')), | |
body: Center( | |
// Consumer is a widget that allows you reading providers. | |
child: Consumer(builder: (context, ref, _) { | |
final count = ref.watch(counterProvider.state).state; | |
return Text('$count'); | |
}), | |
), | |
floatingActionButton: FloatingActionButton( | |
// The read method is a utility to read a provider without listening to it | |
onPressed: () => ref.read(counterProvider.state).state++, | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment