You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:粘性标题固定顶部时如何更新状态

实现粘性标题联动AppBar Elevation的方案

核心思路

通过sticky_headers包提供的onHeaderSticky和onHeaderUnsticky回调,实时更新控制AppBar阴影的状态变量,实现标题粘顶时将AppBar的elevation设为0,离开顶部时恢复默认值的效果。

完整实现代码

import 'package:flutter/material.dart';
import 'package:sticky_headers/sticky_headers.dart';

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

  @override
  State<StickyHeaderAppBarDemo> createState() => _StickyHeaderAppBarDemoState();
}

class _StickyHeaderAppBarDemoState extends State<StickyHeaderAppBarDemo> {
  // 控制AppBar阴影的变量,默认使用Material Design标准值4.0
  double _appBarElevation = 4.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("粘性标题联动AppBar"),
        // 绑定阴影值到状态变量
        elevation: _appBarElevation,
      ),
      body: ListView.builder(
        itemCount: 10,
        itemBuilder: (context, index) {
          return StickyHeader(
            // 粘性标题组件
            header: Container(
              height: 56,
              color: Colors.teal[700],
              padding: const EdgeInsets.symmetric(horizontal: 16),
              alignment: Alignment.centerLeft,
              child: Text(
                "分组标题 $index",
                style: const TextStyle(color: Colors.white, fontSize: 16),
              ),
            ),
            // 标题粘顶时触发的回调
            onHeaderSticky: () {
              setState(() {
                _appBarElevation = 0;
              });
            },
            // 标题离开顶部时触发的回调
            onHeaderUnsticky: () {
              setState(() {
                _appBarElevation = 4.0;
              });
            },
            // 分组内容区域
            content: Container(
              height: 220,
              color: index % 2 == 0 ? Colors.grey[100] : Colors.grey[200],
              child: Center(
                child: Text("分组内容 $index", style: const TextStyle(fontSize: 18)),
              ),
            ),
          );
        },
      ),
    );
  }
}

错误排查与注意事项

  1. 回调必须在State类内部调用setState
    你遇到的错误大概率是因为在非State类中调用setState,或者回调没有正确绑定到State的方法上。确保onHeaderSticky和onHeaderUnsticky的回调逻辑直接写在State类内部,或者通过方法引用绑定到State的成员方法。

  2. 包版本兼容性
    确保sticky_headers包使用最新稳定版,在pubspec.yaml中添加依赖:

    dependencies:
      sticky_headers: ^0.2.0
    

    执行flutter pub get更新依赖。

  3. 避免不必要的状态更新
    回调触发时只更新_appBarElevation变量,不要在回调中执行其他耗时操作,保证滚动流畅性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:45:08