Skip to content

Instantly share code, notes, and snippets.

@nilsreichardt
Created June 14, 2022 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsreichardt/ed7f2b08e980a5e298d806599eefbd93 to your computer and use it in GitHub Desktop.
Save nilsreichardt/ed7f2b08e980a5e298d806599eefbd93 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() => runApp(const ProviderScope(child: MyApp()));
final userProvider = StateProvider<int>((ref) => 1);
final controllerProvider = StateNotifierProvider<ControllerNotifier, int>(
(ref) {
ref.watch(userProvider);
return ControllerNotifier();
},
);
class ControllerNotifier extends StateNotifier<int> {
ControllerNotifier() : super(0) {
timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (mounted) {
state = timer.tick;
} else {
// ignore: avoid_print
print('Still ticking: ${timer.tick}');
}
});
}
late Timer timer;
@override
void dispose() {
timer.cancel();
super.dispose();
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
);
}
}
class Home extends ConsumerWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(title: const Text('Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('User: ${ref.watch(userProvider)}'),
Text('Number: ${ref.watch(controllerProvider)}'),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
ref.read(userProvider.notifier).state++;
},
child: const Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment