You need to enable JavaScript to run this app. Flutter如何实现长滚动页面微滚后显示4个可跳转对应区块的Tab
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何实现长滚动页面微滚后显示4个可跳转对应区块的Tab

实现方案

效果对照

未滚动初始状态滚动后显示Tab状态
未滚动状态页面滚动后显示Tab页面

核心实现思路

采用CustomScrollView配合SliverAppBar实现滚动时的布局联动,通过ScrollController监听滚动偏移量控制Tab显隐,同时绑定Tab和页面区块的双向联动:滚动页面时自动同步Tab选中状态,点击Tab时自动滚动到对应区块。

分步实现步骤

  • 初始化ScrollController监听滚动位置,设置Tab显隐的偏移阈值,阈值大小等于页面初始顶部非Tab区域的高度。
  • 用SliverAppBar作为顶部容器,设置pinned: true保证滚动时AppBar始终吸顶,expandedHeight设置为初始头部的总高度,flexibleSpace放置初始状态展示的顶部内容。
  • 给4个内容区块分别绑定全局唯一GlobalKey,用于定位区块的滚动位置。
  • 给SliverAppBar的bottom属性绑定TabBar,通过AnimatedOpacity实现Tab的平滑显隐效果,滚动偏移超过阈值时显示Tab,低于阈值时隐藏。
  • 监听TabController的点击事件,点击Tab时调用Scrollable.ensureVisible跳转到对应区块的位置,添加过渡动画提升体验。
  • 滚动页面时判断当前可视区域对应的区块,自动切换Tab的选中状态,保持交互同步。

核心实现代码

import 'package:flutter/material.dart';

class LongScrollTabPage extends StatefulWidget {
  const LongScrollTabPage({super.key});

  @override
  State<LongScrollTabPage> createState() => _LongScrollTabPageState();
}

class _LongScrollTabPageState extends State<LongScrollTabPage> with SingleTickerProviderStateMixin {
  final ScrollController _scrollController = ScrollController();
  late TabController _tabController;
  final List<GlobalKey> _sectionKeys = List.generate(4, (index) => GlobalKey());
  // 可根据实际头部高度调整Tab显示阈值
  final double _tabShowThreshold = 200;
  bool _isTabVisible = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _scrollController.addListener(_handleScroll);
    _tabController.addListener(_handleTabTap);
  }

  void _handleScroll() {
    // 控制Tab显隐
    if (_scrollController.offset >= _tabShowThreshold && !_isTabVisible) {
      setState(() => _isTabVisible = true);
    } else if (_scrollController.offset < _tabShowThreshold && _isTabVisible) {
      setState(() => _isTabVisible = false);
    }
    // 同步Tab选中状态
    for (int i = 0; i < _sectionKeys.length; i++) {
      final RenderBox? renderBox = _sectionKeys[i].currentContext?.findRenderObject() as RenderBox?;
      if (renderBox == null) continue;
      final topOffset = renderBox.localToGlobal(Offset.zero).dy;
      if (topOffset <= MediaQuery.of(context).padding.top + kToolbarHeight) {
        if (_tabController.index != i) {
          _tabController.animateTo(i);
        }
        break;
      }
    }
  }

  void _handleTabTap() {
    if (_tabController.indexIsChanging) {
      final targetContext = _sectionKeys[_tabController.index].currentContext;
      if (targetContext != null) {
        Scrollable.ensureVisible(
          targetContext,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          alignment: 0,
        );
      }
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: _scrollController,
        slivers: [
          SliverAppBar(
            pinned: true,
            floating: true,
            expandedHeight: 300,
            title: const Text("长滚动页面"),
            flexibleSpace: FlexibleSpaceBar(
              background: Container(
                // 替换为你的初始头部内容
                color: Colors.blue[100],
                child: const Center(child: Text("顶部自定义头部内容")),
              ),
            ),
            bottom: PreferredSize(
              preferredSize: Size.fromHeight(_isTabVisible ? kTextTabBarHeight : 0),
              child: AnimatedOpacity(
                opacity: _isTabVisible ? 1 : 0,
                duration: const Duration(milliseconds: 200),
                child: TabBar(
                  controller: _tabController,
                  tabs: const [
                    Tab(text: "Tab1"),
                    Tab(text: "Tab2"),
                    Tab(text: "Tab3"),
                    Tab(text: "Tab4"),
                  ],
                ),
              ),
            ),
          ),
          // 内容区块,可替换为实际业务内容
          SliverToBoxAdapter(
            key: _sectionKeys[0],
            child: Container(height: 800, color: Colors.red[100], child: const Center(child: Text("Tab1 内容区域"))),
          ),
          SliverToBoxAdapter(
            key: _sectionKeys[1],
            child: Container(height: 800, color: Colors.green[100], child: const Center(child: Text("Tab2 内容区域"))),
          ),
          SliverToBoxAdapter(
            key: _sectionKeys[2],
            child: Container(height: 800, color: Colors.yellow[100], child: const Center(child: Text("Tab3 内容区域"))),
          ),
          SliverToBoxAdapter(
            key: _sectionKeys[3],
            child: Container(height: 800, color: Colors.purple[100], child: const Center(child: Text("Tab4 内容区域"))),
          ),
        ],
      ),
    );
  }
}

注意事项

  • 代码中的_tabShowThreshold和expandedHeight需要根据你实际的头部布局高度调整,保证Tab显隐时机和视觉效果匹配。
  • 如果页面区块内容是动态高度,建议引入scroll_to_index第三方库替代原生的Scrollable.ensureVisible,定位精度更高,适配性更好。
  • 滚动同步Tab的逻辑可以增加10-20dp的容差值,避免滚动到区块交界处时Tab频繁切换的抖动问题。

内容的提问来源于stack exchange,提问作者Humayun Kabir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:06:03