Created
June 14, 2022 15:22
-
-
Save nilsreichardt/ed7f2b08e980a5e298d806599eefbd93 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 '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