Skip to content

Instantly share code, notes, and snippets.

@hongsw
Created November 15, 2023 02:26
Show Gist options
  • Save hongsw/8048db267587f0182c734315fbe169df to your computer and use it in GitHub Desktop.
Save hongsw/8048db267587f0182c734315fbe169df to your computer and use it in GitHub Desktop.
riverpod example counter with subpage

�riverpod example counter with subpage

Created with <3 with dartpad.dev.

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