Created with <3 with dartpad.dev.
Created
November 15, 2023 02:25
-
-
Save hongsw/9ab5c3ac6c42ae93ceae8a5841432435 to your computer and use it in GitHub Desktop.
riverpod example counter
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'; | |
import 'package:riverpod_annotation/riverpod_annotation.dart'; | |
part 'main.g.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({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp(home: Home()); | |
} | |
} | |
/// Annotating a class by `@riverpod` defines a new shared state for your application, | |
/// accessible using the generated [counterProvider]. | |
/// This class is both responsible for initializing the state (through the [build] method) | |
/// and exposing ways to modify it (cf [increment]). | |
@riverpod | |
class Counter extends _$Counter { | |
/// Classes annotated by `@riverpod` **must** define a [build] function. | |
/// This function is expected to return the initial state of your shared state. | |
/// It is totally acceptable for this function to return a [Future] or [Stream] if you need to. | |
/// You can also freely define parameters on this method. | |
@override | |
int build() => 0; | |
void increment() => state++; | |
void decrease() => state--; | |
} | |
class Home extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Counter example')), | |
body: Center( | |
child: | |
Column(children: [ | |
Text('${ref.watch(counterProvider)}'), | |
TextButton(child: Text('Sub page'), | |
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => SubPage())), | |
) | |
]) | |
), | |
floatingActionButton: FloatingActionButton( | |
// The read method is a utility to read a provider without listening to it | |
onPressed: () => ref.read(counterProvider.notifier).increment(), | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} | |
class SubPage extends ConsumerWidget { | |
const SubPage({super.key}); | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Counter example ${ref.watch(counterProvider)}')), | |
body: Text('Sub page') | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment