1、添加依赖
在pubspec.yaml中引入依赖
dependencies:
provide: ^1.0.2 #数据管理层
执行,当然,如果是vscode,保存yaml的时候,会自动get
flutter packages get2、新建状态管理文件 bottom_navigation_bar_index.dart ,这里以首页‘BottomNavigationBar’的‘currentIndex’为例,因为可能在子页面,也会更改这个‘BottomNavigationBar’的index,所以最好定义成provide。
3、在 bottom_navigation_bar_index.dart 定义一个类,这个类继承 ChangeNotifier,并且含有表示 currentIndex 的变量以及修改这个变量的方法 changeIndex:
import 'package:flutter/material.dart';
class BottomNavigationBarIndex with ChangeNotifier{
int currentIndex = 0;
void changeIndex(int idx){
this.currentIndex = idx;
//当currentIndex改变时,通知使用这个状态的页面刷新
notifyListeners();
}
}
4、全局注入,改造 main.dart
//状态管理
import 'package:provide/provide.dart';
import './provide/bottom_navigation_bar_index.dart';
void main(){
//状态管理provide注入
var providers = Providers();
providers..provide(Provider<BottomNavigationBarIndex>.value(BottomNavigationBarIndex()))
runApp(ProviderNode(
child:MyApp(),
providers: providers,
)
);
}
5、使用这个状态
//状态管理provide -- 一个状态
return Provide<BottomNavigationBarIndex>(
builder: (context,child,bottomNavigationBarIndex){
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
//使用刚才定义的状态
currentIndex: bottomNavigationBarIndex.currentIndex,
items: _bottomTabs(),
onTap: (index){
//调用刚才定义的changeIndex方法,修改currentIndex的值
bottomNavigationBarIndex.changeIndex(index);
},
unselectedItemColor: Color.fromRGBO(160, 160, 160, 1),
selectedItemColor: Color.fromRGBO(33, 139, 219, 1),
unselectedFontSize: ScreenUtil().setSp(20),
selectedFontSize: ScreenUtil().setSp(20),
),
body: IndexedStack( //IndexedStack 层叠组建,可以保持状态而不至于销毁其他页面
//使用刚才定义的状态
index: bottomNavigationBarIndex.currentIndex,
children:[
HomePage(),
AddPage(),
MessagePage(),
MinePage()
],
),
);
},
);
这个只是简单使用,如果遇到有多个状态同时使用,这种方法就不行了,参见:flutter ProvideMulti多个状态同时使用