tazboy

Untitled

Dec 13th, 2020
97
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /***** main.dart *****/
  2. class DiceNotifier extends ChangeNotifier {
  3.   List<DieWidget> dice = [];
  4.  
  5.   void add() {
  6.     dice.add(DieWidget());
  7.     notifyListeners();
  8.   }
  9.  
  10.   void removeDie(int id) {
  11.     print(id);
  12.     notifyListeners();
  13.   }
  14. }
  15.  
  16. final diceProvider = ChangeNotifierProvider((_) {
  17.   return DiceNotifier();
  18. });
  19.  
  20. class MyHomePage extends ConsumerWidget {
  21.   @override
  22.   Widget build(BuildContext context, ScopedReader watch) {
  23.     final dice = watch(diceProvider).dice;
  24.     return Scaffold(
  25.       appBar: AppBar(
  26.         title: Text("Dice"),
  27.       ),
  28.       body: Center(
  29.         child: Column(
  30.           mainAxisAlignment: MainAxisAlignment.center,
  31.           children: <Widget>[
  32.             ...dice,
  33.           ],
  34.         ),
  35.       ),
  36.       floatingActionButton: FloatingActionButton(
  37.         onPressed: () {
  38.           context.read(diceProvider).add();
  39.         },
  40.         child: Icon(Icons.add),
  41.       ), // This trailing comma makes auto-formatting nicer for build methods.
  42.     );
  43.   }
  44. }
  45.  
  46. /***** die_widget.dart *****/
  47. class DieWidget extends StatefulWidget {
  48.   @override
  49.   _DieWidgetState createState() => _DieWidgetState();
  50. }
  51.  
  52. class _DieWidgetState extends State<DieWidget> {
  53.   int value = 0;
  54.   int id = 0;
  55.   @override
  56.   Widget build(BuildContext context) {
  57.     return FlatButton(
  58.       child: Text(
  59.         '$value',
  60.       ),
  61.       onPressed: () {
  62.         setState(() {
  63.           value++;
  64.           id++;
  65.         });
  66.         // context.read(dieProvider).increment();
  67.       },
  68.       onLongPress: () {
  69.         final dice = context.read(diceProvider);
  70.         dice.removeDie(id);
  71.         // print(this.value);
  72.       },
  73.     );
  74.   }
  75. }
RAW Paste Data