官网:https://pub.dev/packages/provider
1.引入依赖
provider: ^4.3.0
2.新建文件夹Provider 用于管理状态
3.新建文件cate.dart
import 'package:flutter/material.dart'; class MainProvide extends ChangeNotifier{ int curNum=0; add(){ curNum+=1; notifyListeners(); } minus(){ curNum -= 1; notifyListeners(); } }
4.在需要引用的地方引入
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../provider/cart.dart'; import '../provider/cart2.dart'; class CartPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Container( child: MultiProvider( providers: [ ChangeNotifierProvider( create: (context){ return MainProvide(); } ), ChangeNotifierProvider( create: (context){ return MainProvide2(); } ) ],child: Column( children: <Widget>[ Number(), MyButton() ], ), ), ) ); } } class Number extends StatelessWidget { @override Widget build(BuildContext context) { MainProvide provider=Provider.of<MainProvide>(context); MainProvide2 provider2=Provider.of<MainProvide2>(context); int curNum=provider.curNum; int curNum2=provider2.curNum; return Container( margin: EdgeInsets.only(top:200), child: Column( children: <Widget>[ Text('$curNum'), Text('$curNum2'), ], ) ); } } class MyButton extends StatelessWidget { @override Widget build(BuildContext context) { MainProvide provider=Provider.of<MainProvide>(context); MainProvide2 provider2=Provider.of<MainProvide2>(context); return Container( child: RaisedButton( onPressed: (){ provider.add(); provider2.add(); }, child: Text('递增'), ), ); } }