Flutter 03:PageView多页面切换组件

3,439 阅读1分钟

基本概念

PageView({
    Key key, 
    Axis scrollDirection: Axis.horizontal, //方向
    bool reverse: false, //是否和阅读方向一样的滚动,比如中文的阅读习惯系从左往右
    PageController controller, //控制器
    ScrollPhysics physics, //页面视图如何响应用户输入
    bool pageSnapping: true, //使用自定义滚动时禁止页面捕捉
    ValueChanged<int> onPageChanged, //页面切换回调
    List<Widget> children: const [], //页面(组件)列表,页面个数等于长度
    DragStartBehavior dragStartBehavior: DragStartBehavior.start //拖拽行为
})
PageView.builder({
    ...
    @required IndexedWidgetBuilder itemBuilder, //创建item,根据回调index返回不同页面
    int itemCount, //item数量
    ...
})
PageView.custom({
    ...
    @required SliverChildDelegate childrenDelegate, //自定义模式接受一个子页面委托对象
    ...
})

作用:滑动切换页面

实例

//初始化
final PageController _pageController = PageController(initialPage: 0);
final List<Widget> _bodyPages = [HomePage(), TreePage(),NaviPage(),ProjectPage()];

body: PageView.builder( //实现滑动切换
    onPageChanged: (int index){ //页面改变监听
      //todo
    },
    controller: _pageController, //页面控制器
    itemCount: _bodyPages.length, //即页面数量
    itemBuilder: (BuildContext context, int index){ //页面加载器
      return _bodyPages.elementAt(index);
    }
 ),
 
 _pageController.animateToPage(index, duration: Duration(milliseconds: 300), curve: Curves.ease);

关于PageController

PageController({
    this.initialPage = 0,    //初始化选择页面
    this.keepPage = true,    //是否保持已经渲染过得页面
    this.viewportFraction = 1.0,  //每个页面应占用的视口部分。 0~1之间
 })

控制器跳转有4个已有的方法

  • animateToPage:带动画跳转
  • jumpToPage:直接改变当前页面无动画
  • nextPage:下一页
  • previousPage:上一页
_pageController.jumpToPage(_selectedIndex);