Flutter 滚动距离来设置TabBar的位置,点击TabBar滚动的到指定的位置

效果gif

在这里插入图片描述

定义属性

   ScrollController _controller = new ScrollController();
  var globalKeyOne = GlobalKey();
  var globalKeyTwo = GlobalKey();
  var globalKeyThree = GlobalKey();
  var oneY = 0.0;
  var twoY = 0.0;
  var threeY = 0.0;

每个组件设置Key

return ListView(
      controller: _controller,
      children: <Widget>[
        Container(
          key: globalKeyOne,
          height: AppSize.height(300),
          color: Colors.blue,
          child: Text("商品"),
        ),
        Container(
          key: globalKeyTwo,
          color: Colors.green,
          height: AppSize.height(700),
          child: Text("详情"),
        ),
        Container(
          key: globalKeyThree,
          color: Colors.orange,
          height: AppSize.height(1500),
          child: Text("评价"),
        )
      ],
    );

获取控件的距离顶部的位置

   oneY = getY(globalKeyOne.currentContext);
    twoY = getY(globalKeyTwo.currentContext);
    threeY = getY(globalKeyThree.currentContext);

设置监听

_controller.addListener(() {
      var of = _controller.offset;
      if (of > threeY - oneY) {
        _tabController.animateTo(2);
      }else if (of > twoY - oneY) {
        _tabController.animateTo(1);
      } else {
        _tabController.animateTo(0);
      }

设置TabBar 点击

 child: TabBar(
          onTap: (index){
            switch(index){
              case 0:
                _controller.jumpTo(0);
                _tabController.animateTo(0);
                break;
              case 1:
                _controller.jumpTo(twoY - oneY);
                _tabController.animateTo(1);
                break;
              case 2:
                _controller.jumpTo(threeY - oneY);
                _tabController.animateTo(2);
                break;
            }

          },

getY

double getY(BuildContext buildContext){
  final RenderBox box = buildContext.findRenderObject();
  //final size = box.size;
  final topLeftPosition = box.localToGlobal(Offset.zero);
  return topLeftPosition.dy;
}

源码 感觉有用的话,star一下

github地址

如果想一起学习进步 QQ群766903559

发布了96 篇原创文章 · 获赞 12 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/yujunlong3919/article/details/105107195