1.1. IndexedStack 和 Stack 一样,都是层布局控件,可以在一个控件上面放置另一 个控件,但唯一不同的是 IndexedStack 在同一时刻只能显示子控件中的一个控 件,通过 Index 属性来设置显示的控件。
1.2. IndexedStack 来保持页面状态优缺点:
1.2.1: 优点:配置简单;
1.2.2: 缺点:不方便单独控制每个页面的状态(有的页面不需要缓存,需要每次都加载.例如:购物车),
1.3. IndexedStack相当于与将所有的页面或组件一次性全部放入容器中,然后通过index取出对应的页面或组件,放置在对顶层.
Container(
width: double.infinity,
height: double.infinity,
child: new IndexedStack(
index: 0,
alignment: Alignment.center,
children: [
Image.network(
"https://www.itying.com/images/flutter/list1.jpg",
fit: BoxFit.cover,
),
Image.network("https://www.itying.com/images/flutter/list2.jpg",
fit: BoxFit.cover)
],
),
),
body:IndexedStack(
children: this._pageList,
index: _currentIndex,
),
他可以单独控制某一个页面是否需要缓存(控制某一个页面是否需要重新加载).
void main() {
return runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State createState() => _MyAppState();
}
class _MyAppState extends State {
//创建4个试图,进行tabbar切换
final List vcArray = const [
HomeVC(),
BusinessVC(),
workRoomVC(),
MyVC()
];
//默认选择第0个试图.即首页
int _currentIndex = 0;
//2.1 初始化PageController
late PageController _keepActiveVC;
@override
void initState() {
super.initState();
//页面控制器初始化
_keepActiveVC = PageController(initialPage: _currentIndex);
}
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: "***",
theme: ThemeData(
primaryColor: PublicColor.mainColor,
),
home: (Scaffold(
//2.2.视频必须使用PageView进行包裹
body: PageView(
controller: _keepActiveVC,//初始化的PageController
children: vcArray,//当前所有视图的数组
onPageChanged: (index) {
_currentIndex = index;//切换选中的时候进行赋值
},
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,//当前选中的索引值
selectedItemColor: PublicColor.mainColor,
unselectedItemColor: PublicColor.mainGray,
onTap: (index) {
setState(() {
_currentIndex = index;
//2.3.使用PageController调用jumpToPage()方法
_keepActiveVC.jumpToPage(index);
});
},
items: [
BottomNavigationBarItem(
),
BottomNavigationBarItem(
),
]),
)),
);
}
}
class HomeVC extends StatefulWidget {
const HomeVC({super.key});
@override
State createState() => _HomeVCState();
}
class _HomeVCState extends State with AutomaticKeepAliveClientMixin {
@override
//1.必须with AutomaticKeepAliveClientMixin;
//2.实现get wantKeepAlive方法.当前页面需要缓存到的时候返回true,否则返回flase.默认是flase
bool get wantKeepAlive => true;
}