Flutter - PageView(1) 基本用法

如果要实现页面切换和 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 界面
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值