flutter实战项目02 状态管理

设置状态管理仓库provide/provide.dart

import 'package:flutter/material.dart';

class CurrentIndexProvide with ChangeNotifier{
  int currentIndex = 0;
  changeIndex(int newIndex){
    currentIndex = newIndex;
    notifyListeners();
  }
}

最外层引入providers main.dart

import './provide/current_index_provide.dart';
import 'package:provide/provide.dart';

void main(){
  var currentIndexProvide = CurrentIndexProvide();
  var providers = Providers();

  providers
    ..provide(Provider<CurrentIndexProvide>.value(currentIndexProvide));
  runApp(ProviderNode(child: MyApp(),providers: providers));
}

获取和改变仓库值pages/index_page.dart

import "package:flutter/material.dart";
import 'package:provide/provide.dart';

return Provide<CurrentIndexProvide>(
      builder: (context,child,val){
			//获取currentIndex  val.currentIndex
			int currentIndex = Provide.value<CurrentIndexProvide>(context).currentIndex;
			//改变currentIndex
			Provide.value<CurrentIndexProvide>(context).changeIndex(index);
		}
)

状态管理之导航切换示例

class IndexPage extends StatefulWidget{
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>{
  final List<BottomNavigationBarItem> bottomTabs = [
    BottomNavigationBarItem(icon: Icon(Icons.home),title:Text(KeyString.homeTitle)),
    BottomNavigationBarItem(icon: Icon(Icons.category),title:Text(KeyString.category)),
    BottomNavigationBarItem(icon: Icon(Icons.shopping_cart),title:Text(KeyString.shopping_cart)),
    BottomNavigationBarItem(icon: Icon(Icons.person),title:Text(KeyString.person)),
  ];
  final List<Widget> tabBodies = [
    HomePage(),
    CategoryPage(),
    ShoppingCartPage(),
    PersonPage()
  ];
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 755,height: 1334)..init(context);
    return Provide<CurrentIndexProvide>(
      builder: (context,child,val){
        //取到当前索引状态值
        int currentIndex = Provide.value<CurrentIndexProvide>(context).currentIndex;
        return Scaffold(
          backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
          bottomNavigationBar: BottomNavigationBar(
            type: BottomNavigationBarType.fixed,
            currentIndex: currentIndex,
            items: bottomTabs,
            onTap: (index){
              Provide.value<CurrentIndexProvide>(context).changeIndex(index);
            },
          ),
          //IndexedStack在同一时刻只能显示子控件中的一个控件,通过Index属性来设置显示的控件
          body: IndexedStack(
            index: currentIndex,
            children: tabBodies,
          ),
        );
      },
    );
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值