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

如何在Flutter中实现Material 3的中小型应用栏标题滚动展开效果?

实现Material3滚动标题展开效果

可以通过Flutter的SliverAppBar配合Material3主题实现你需要的效果,核心是利用展开高度配置、弹性空间组件来实现滚动时标题的动态变化行为。

以下是完整的可运行示例代码:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        useMaterial3: true, // 启用Material3设计规范
        colorSchemeSeed: Colors.blue,
      ),
      home: const Scaffold(
        body: CustomScrollView(
          slivers: [
            _ExpandingTopAppBar(),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) => ListTile(title: Text('列表项 $index')),
                childCount: 50,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ExpandingTopAppBar extends StatelessWidget {
  const _ExpandingTopAppBar();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SliverAppBar(
      expandedHeight: 200, // 设置AppBar展开时的总高度
      pinned: true, // 滚动时保持AppBar顶部区域固定
      flexibleSpace: FlexibleSpaceBar(
        title: const Text('动态展开标题'),
        titlePadding: const EdgeInsets.all(16),
        // 分别配置展开/收起状态下的标题样式
        titleLargeStyle: theme.textTheme.headlineMedium?.copyWith(
          color: theme.colorScheme.onSurface,
        ),
        titleSmallStyle: theme.textTheme.titleLarge?.copyWith(
          color: theme.colorScheme.onSurface,
        ),
        background: Container(color: theme.colorScheme.surfaceVariant),
      ),
    );
  }
}

关键实现要点:

  • 必须开启useMaterial3: true,确保组件行为遵循Material3设计规范
  • expandedHeight定义了AppBar完全展开时的高度,滚动时会自动收缩至默认导航栏高度
  • FlexibleSpaceBar的titleLargeStyle和titleSmallStyle分别对应标题在展开、收起状态下的样式,匹配Material3中Large Top App Bar的交互逻辑
  • pinned: true保证导航栏始终固定在顶部,仅标题区域随滚动动态变化

如果需要更精细的动画控制,可以结合ScrollController监听滚动偏移量,手动调整标题的位置、大小等属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:30:00