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,
          ),
        );
      },
    );
  }
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页