1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| import 'package:flutter/material.dart'; import 'package:flutter_demo/provider/main_provider.dart'; import 'package:provider/provider.dart';
void main() { runApp(MaterialApp( title: 'demo', theme: ThemeData( primarySwatch: Colors.blue, ), //定义作用区间 只绘制顶层home home: MultiProvider( providers: [ ChangeNotifierProvider(builder: (_) => MainProvider()), ], child: Home(), ), )); }
class Home extends StatefulWidget { @override _HomeState createState() => new _HomeState(); }
class _HomeState extends State<Home> { // int curNum = 0; int curNum;
@override void initState() { super.initState(); //TODO }
void add() { setState(() { curNum += 1; }); //TODO }
void minus() { setState(() { curNum -= 1; }); //TODO }
@override Widget build(BuildContext context) { //定义provider 实例化 MainProvider provider = Provider.of<MainProvider>(context); curNum = provider.curNum; return new Scaffold( appBar: new AppBar( title: new Text('demo'), ), body: Column( children: <Widget>[ Add(), // Add( // add: add, // ), Container( child: Text( '$curNum', style: TextStyle(fontSize: 30), ), ), Minus(), // Minus( // minus: minus, // ), ], ), ); } }
class Minus extends StatelessWidget { const Minus({ Key key, // this.minus, }) : super(key: key); // final int curNum; // final VoidCallback minus; @override Widget build(BuildContext context) { MainProvider provider = Provider.of<MainProvider>(context); return Container( child: Container( child: FlatButton( child: Text( '-', style: TextStyle(fontSize: 30), ), onPressed: () { provider.minus(); }, ), ), ); } }
class Add extends StatelessWidget { const Add({ Key key, // this.add, }) : super(key: key); // final int curNum; // final VoidCallback add; @override Widget build(BuildContext context) { MainProvider provider = Provider.of<MainProvider>(context); return Container( child: Container( child: FlatButton( child: Text( '+', style: TextStyle(fontSize: 30), ), onPressed: () { provider.add(); }, ), ), ); } }
|