我爱模板网 > 建站教程 > APP开发,混合APP >  flutter Provide状态管理的简单使用正文

flutter Provide状态管理的简单使用

flutter Provide状态管理有点类似于Vuex,当从一个页面更改了数据,期望影响其他页面,那么Provide方法是不二之选。这里简单理下我爱模板网在使用flutter时的用法:

1、添加依赖
    在pubspec.yaml中引入依赖
dependencies:
    provide: ^1.0.2 #数据管理层
    执行,当然,如果是vscode,保存yaml的时候,会自动get
flutter packages get
2、新建状态管理文件 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多个状态同时使用


部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!
上一篇:The Android Gradle plugin supports only Kotlin Gradle plugin 下一篇:flutter ProvideMulti多个状态同时使用
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
选择头像:
最新评论

猜你喜欢