flutter实战项目02 状态管理

provide/provide.dart

import 'package:flutter/material.dart';

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

pages/index_page.dart

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

//获取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,
          ),
        );
      },
    );
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_45561719/article/details/107886303