tazboy

Untitled

Dec 12th, 2020
92
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /***** main.dart *****/
  2. // These calls are inside a column inside build
  3. DieWidget(),
  4. DieWidget(),
  5.  
  6. /***** die.dart *****/
  7. class Die {
  8.   int value;
  9.   Die({this.value});
  10. }
  11.  
  12. class DieNotifier extends StateNotifier<Die> {
  13.   DieNotifier([Die die]) : super(die ?? Die(value: 4));
  14.  
  15.   void increment() {
  16.     state = Die(value: state.value + 1);
  17.   }
  18. }
  19.  
  20. /***** die_widget.dart *****/
  21. final dieProvider = StateNotifierProvider<DieNotifier>((ref) {
  22.   return DieNotifier();
  23. });
  24.  
  25. class DieWidget extends ConsumerWidget {
  26.   @override
  27.   Widget build(BuildContext context, ScopedReader watch) {
  28.     final die = watch(dieProvider.state);
  29.     return FlatButton(
  30.       child: Text(
  31.         '${die.value}',
  32.       ),
  33.       onPressed: () {
  34.         context.read(dieProvider).increment();
  35.       },
  36.     );
  37.   }
  38. }
RAW Paste Data