如果要实现页面切换和 Tab 布局,我们可以使用 PageView 组件。需要注意,PageView 是一个非常重要的组件,因为在移动端开发中很常用,比如大多数 App 都包含 Tab 换页效果、图片轮动以及抖音上下滑页切换视频功能等等,这些都可以通过 PageView 轻松实现。
1 PageView 简单使用
PageView(
scrollDirection:Axis.horizontal,
allowImplicitScrolling: true,
children: <Widget>[
MyItemContainerState(colors: Colors.yellow,pageName: "yellow",),
MyItemContainerState(colors: Colors.red,pageName: "red",),
MyItemContainerState(colors: Colors.green,pageName: "green",),
MyItemContainerState(colors: Colors.blue,pageName: "blue",),
MyItemContainerState(colors: Colors.deepPurple,pageName: "deepPurple",)
],
)
class MyItemContainerState extends StatefulWidget {
const MyItemContainerState({Key? key,required this.colors,required this.pageName}) : super(key: key);
final MaterialColor colors ;
final String pageName ;
State<MyItemContainerState> createState() {
// TODO: implement createState
return ItemContainerState(colors,pageName);
}
}
class MyItemContainerState extends StatefulWidget {
const MyItemContainerState({Key? key,required this.colors,required this.pageName}) : super(key: key);
final MaterialColor colors ;
final String pageName ;
State<MyItemContainerState> createState() {
// TODO: implement createState
return ItemContainerState(colors,pageName);
}
}
class ItemContainerState extends State<MyItemContainerState> with AutomaticKeepAliveClientMixin{
MaterialColor colors ;
String pageName ;
ItemContainerState(this.colors,this.pageName);
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
Widget build(BuildContext context) {
super.build(context);
print("创建$pageName");
// TODO: implement build
return Container(
width: double.infinity,
height: double.infinity,
color: colors,
alignment: Alignment.center,
child: Text(pageName,style: TextStyle(fontSize: 50,color: Colors.white),),
);
}
void dispose() {
// TODO: implement dispose
print("销毁$pageName");
super.dispose();
}
}
注1 scrollDirection:Axis.horizontal,
控制PageView的滑动方向
Axis.horizontal 是横着滑
Axis.vertical 竖着滑
注 2 allowImplicitScrolling: true,
为true 时 ,缓存当前页的前一页和后一页
为false 时 ,不缓存,滑出当前页及时销毁当前页
1 下面日志打印的是 allowImplicitScrolling = false 的情况
2 下面是 allowImplicitScrolling = true 的情况
2.1第一次运行程序,创建了 yellow 和 red 两个界面
2.2 滑动到第二个界面是 创建了 green 界面 ,并且没有销毁 yellow 界面
2.3 滑动到第三个green界面时 创建了 blue 界面 且销毁了yellow 界面