flutter PageView与TabBarView嵌套滚动的实现

参考:github项目地址

我这边是的App的首页是PageView里加了5个页面,其中有一个页面是包含了TabBarView。在滚动的过程中,当TabBarView滚动到最后一页或者第一页面的时候,不能和PageView进行联动。所以查询了很多种方式,觉的上面作者实现的方式很不错。代码量不多。

1.创建一个PageViewScrollUtils助手类,当监听的需要的时机,进行相应的操作

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class PageViewScrollUtils {
  final PageController pageController;
  final TabController tabController;
  PageViewScrollUtils({required this.pageController, required this.tabController});

  Drag? _drag;

  bool handleNotification(ScrollNotification notification) {
    if (notification is UserScrollNotification) {
      if ((notification.direction == ScrollDirection.reverse && tabController.index == tabController.length - 1) || (notification.direction == ScrollDirection.forward && tabController.index ==  0)) {
        _drag = pageController.position.drag(DragStartDetails(), () {
          _drag = null;
        });
      }
    }
    if (notification is OverscrollNotification) {
      if (notification.dragDetails != null && _drag != null) {
        _drag!.update(notification.dragDetails!);
      }
    }
    if (notification is ScrollEndNotification) {
      if (notification.dragDetails != null && _drag != null) {
        _drag!.end(notification.dragDetails!);
      }
    }
    return true;
  }
}

2.在TabBarView所在的页面实例化PageViewScrollUtils,实例化的时候需要TabBarView与PageView的controller

_pageViewScrollUtils = PageViewScrollUtils(pageController: widget.pageController,tabController: _tabController);

3.在TabBarView 外边套一个NotificationListener,监听TabBarView滚动,并使用PageViewScrollUtils进行处理

NotificationListener(
                    child: TabBarView(
                          physics: ClampingScrollPhysics(),
                          controller: _tabController,
                          children: [
                            LobbyLayout(),
                            LobbyLayout(),
                            LobbyLayout(),
                            LobbyLayout()
                          ]
                      ),
                      onNotification: _pageViewScrollUtils.handleNotification,
                    )

4.这样就可以了。非常简单,代码量也很少。

点击下方赞赏,给作者一点鼓励!

你可能感兴趣的:(flutter PageView与TabBarView嵌套滚动的实现)