简介
" 本文正在参加「金石计划」 ”
Flutter作为跨平台的优秀语言,值得每一位开发者学习,今天给大家带来PageView和IndexedStack在使用中的对比,相信很多开发的同学都遇到过这样的场景,点击应用底部的导航栏切换页面。如此简单的需要相信大家很轻松完成。
在Flutter中,系统给我们提供了BottomNavigationBar用来实现底部导航栏。展示的页面可以使用很多布局控件实现。如:PageView,IndexedStack,Container等。本文主要讲解PageView和IndexedStack在实现上的差异,帮助开发同学选择合适的实现方案。“
IndexedStack
IndexedStack 是层叠布局,继承于Stack类。层叠布局意味着布局都是堆叠在一起的。类似Android里面FramLayout。先来看构造函数。
class IndexedStack extends Stack {
IndexedStack({
super.key,
super.alignment,
super.textDirection,
super.clipBehavior,
StackFit sizing = StackFit.loose,
this.index = 0,
super.children,
})
......
}
常用参数
- index: 当前显示view的下标
- children:子view的集合
- alignment:对齐方式
- textDirection:子view的显示方向
- clipBehavior:设置裁剪方式
IndexedStack默认只显示一个子view。当初始化页面时,IndexedStack内部的所有子View都会被初始化。用户可以根据 index下标来切换需要显示的子view。类似Android原生控件ViewAnimator。对ViewAnimator不熟悉的同学,需要自己查阅一下Android原生控件。
基本使用
IndexedStack{
index:0,
children:[Center()]
}
PageView
PageView是一个逐页显示的可滚动的布局控件。类似Android原生的ViewPage。其构造函数如下:
PageView({
super.key,
this.scrollDirection = Axis.horizontal,
this.reverse = false,
PageController? controller,
this.physics,
this.pageSnapping = true,
this.onPageChanged,
List<Widget> children = const <Widget>[],
this.dragStartBehavior = DragStartBehavior.start,
this.allowImplicitScrolling = false,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
this.scrollBehavior,
this.padEnds = true,
})
常用参数
- scrollDirection:页面滑动方向,Axis.horizontal 水平左右滑动。 Axis.vertical 上下滑动。
- onPageChanged:滑动回调
- children:子view集合
- scrollBehavior:滑动样式
- pageSnapping: 每次滑动是否强制切换整个页面,如果为false,则会根据实际的滑动距离显示页面
使用PageView加载页面时,默认加载当前页面数据,当页面从第一页切换到第二页,然后返回到第一页时。控制台打印如下:
flutter :pageIndex 0
flutter: :pageIndex 1
flutter: :pageIndex 0
从打印的信息可以看出,PageView默认是没有页面缓存功能的,这点和Android原生ViewPager不同。
基本使用
Scaffold(
appBar: AppBar(
title: Text(_titleList[currentIndex]),
actions: const [
Padding(padding: EdgeInsets.only(right: 10),child: Icon(Icons.search,color: Colors.white,),)
],
),
body:PageView(
controller: _controller,
children: _pageList,
),
bottomNavigationBar: BottomNavigationBar(items: _initItems(),
currentIndex: currentIndex,
onTap: (index){
setState(() {
_controller.jumpToPage(currentIndex);
});
}
一般使用PageView只需要controller控制器,和chaildren集合就行。controller是PageController。点击底部的BottomNavigationBar时,调用controller.jumpToPage切换指定下标的页面。
IndexedView对比PageView
- IndexedView适用于根据条件显示多个View其中的一个,根据下标Index指定显示的子view,但是对于列表页面则不适用,一般列表页面数据量较大,当加载IndexedView时会同时加载其内部的所有view。
- PageView可以实现按需加载,当切换到指定页面时才主动加载数据,同时支持上下,左右页面切换。
- 如果PageView需要实现页面缓存,可以在子页面中混入AutomaticKeepAliveClientMixin,实现其wantKeepAlive方法,返回true,可以使其页面再次返回第一页时,页面数据不会重新加载。或者结合KeepLiveWrapper控件使用。
总结
PageView可以实现Android原生ViewPager的功能。配合TabBar或BottomNavigationBar可以实现顶部或底部页面导航。而IndexedStack适合较少页面且数据量不大的页面切换。
通过本篇文章的介绍,希望能给正在学习Flutter的同学一点帮助,如有不对的地方,请指正。