SliverAppBar collapsible in Flutter: solved exercise

SliverAppBar collapsible in Flutter: solved exercise

AppBar is fixed. SliverAppBar inside a CustomScrollView expands, collapses, and pins based on scroll position, creating the collapsing header effect you see in social media profiles or product detail screens.

Problem statement

Create a profile screen with:

  • A collapsible header with a background image and username.
  • Tabs that pin to the top when the header fully collapses.
  • A content list with 30 items below the tabs.
  • A floating action button that hides when scrolling down and reappears when scrolling up.

Dependencies

Flutter SDK only.

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

void main() => runApp(const MaterialApp(home: ProfilePage()));

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

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with SingleTickerProviderStateMixin {
  late final TabController _tabController;
  late final ScrollController _scrollController;
  bool _fabVisible = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _scrollController = ScrollController()
      ..addListener(() {
        // Hide FAB when scrolling down, show when scrolling up
        final direction = _scrollController.position.userScrollDirection;
        setState(() {
          _fabVisible = direction != ScrollDirection.reverse;
        });
      });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: AnimatedScale(
        scale: _fabVisible ? 1 : 0,
        duration: const Duration(milliseconds: 200),
        child: FloatingActionButton(
          onPressed: () {},
          child: const Icon(Icons.add),
        ),
      ),
      body: CustomScrollView(
        controller: _scrollController,
        slivers: [
          // ── Collapsible header ───────────────────────────────────────────
          SliverAppBar(
            expandedHeight: 260,
            pinned: true,    // stays visible when collapsed
            floating: false,
            stretch: true,   // stretches on overscroll (iOS style)
            flexibleSpace: FlexibleSpaceBar(
              title: const Text(
                'Ana GarcΓ­a',
                style: TextStyle(
                  shadows: [Shadow(blurRadius: 8, color: Colors.black54)],
                ),
              ),
              background: Stack(
                fit: StackFit.expand,
                children: [
                  // Header image (replace with NetworkImage in production)
                  Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [Color(0xFF1a3a5c), Color(0xFF4fc3f7)],
                      ),
                    ),
                  ),
                  // Centered avatar
                  Positioned(
                    bottom: 48,
                    left: 0,
                    right: 0,
                    child: Center(
                      child: CircleAvatar(
                        radius: 44,
                        backgroundColor: Colors.white,
                        child: CircleAvatar(
                          radius: 40,
                          backgroundColor: Colors.blue.shade200,
                          child: const Icon(Icons.person, size: 40, color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              collapseMode: CollapseMode.parallax,
            ),
          ),

          // ── Profile stats ────────────────────────────────────────────────
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: const [
                  _StatItem(value: '142', label: 'Posts'),
                  _StatItem(value: '4.2K', label: 'Followers'),
                  _StatItem(value: '318', label: 'Following'),
                ],
              ),
            ),
          ),

          // ── Pinned tabs ──────────────────────────────────────────────────
          SliverPersistentHeader(
            pinned: true,
            delegate: _TabBarDelegate(
              TabBar(
                controller: _tabController,
                tabs: const [
                  Tab(icon: Icon(Icons.grid_on)),
                  Tab(icon: Icon(Icons.bookmark_border)),
                  Tab(icon: Icon(Icons.person_outline)),
                ],
              ),
            ),
          ),

          // ── Content list ─────────────────────────────────────────────────
          SliverList.builder(
            itemCount: 30,
            itemBuilder: (_, index) => ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.blue.shade100,
                child: Text('${index + 1}'),
              ),
              title: Text('Post number ${index + 1}'),
              subtitle: const Text('2 hours ago · ❀️ 24 comments'),
              trailing: const Icon(Icons.more_vert),
            ),
          ),
        ],
      ),
    );
  }
}

// ── Helper widgets ────────────────────────────────────────────────────────────

class _StatItem extends StatelessWidget {
  final String value;
  final String label;
  const _StatItem({required this.value, required this.label});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(value, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
        const SizedBox(height: 2),
        Text(label, style: TextStyle(color: Colors.grey.shade600, fontSize: 12)),
      ],
    );
  }
}

/// Delegate for SliverPersistentHeader with fixed height (TabBar).
class _TabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar tabBar;
  const _TabBarDelegate(this.tabBar);

  @override
  double get minExtent => tabBar.preferredSize.height;
  @override
  double get maxExtent => tabBar.preferredSize.height;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return ColoredBox(
      color: Theme.of(context).scaffoldBackgroundColor,
      child: tabBar,
    );
  }

  @override
  bool shouldRebuild(_TabBarDelegate old) => old.tabBar != tabBar;
}

Expected result

  • Scrolling down collapses the image header, leaving only the AppBar with the name.
  • Tabs pin just below the AppBar and never scroll out of view.
  • The FAB smoothly hides when scrolling down and reappears when scrolling up.

Key SliverAppBar parameters

ParameterEffect
pinned: trueCollapsed AppBar stays visible
floating: trueAppBar reappears on first upward scroll
snap: trueRequires floating: true; AppBar snaps fully open when appearing
stretch: trueStretches on overscroll (iOS style)
expandedHeightMaximum height when fully expanded

Common mistakes

  • SliverAppBar outside CustomScrollView: throws FlutterError: SliverAppBar must be used inside a CustomScrollView.
  • Using Scaffold.appBar together with SliverAppBar: two AppBars appear. Use only one.
  • SliverPersistentHeader without a delegate: the abstract class requires an implementation; for simple cases use SliverToBoxAdapter instead.

Practical use

Profile screens, product cards in e-commerce, lists with informational headers, and any UI where the main content needs to maximize reading space.

Guided practice and next step

FAQ

How do I add a real network image as the background?

Replace the gradient Container with:

1
Image.network(url, fit: BoxFit.cover)

Inside the Stack of FlexibleSpaceBar.background.

How do I get the parallax effect?

Use collapseMode: CollapseMode.parallax in FlexibleSpaceBar. With CollapseMode.pin the background stays fixed; with parallax it moves slower than the scroll, creating depth.

Can I have multiple SliverLists in the same CustomScrollView?

Yes. Add as many slivers as you need to the slivers: [...] list. They render in vertical order.