How to Use CustomScrollView in Flutter: Syntax and Example
Use
CustomScrollView in Flutter to create scrollable areas with multiple scrollable widgets called slivers. Wrap slivers like SliverAppBar or SliverList inside CustomScrollView to build flexible scrolling effects.Syntax
The CustomScrollView widget takes a list of slivers, which are scrollable areas that can be combined to create complex scrolling effects.
Common slivers include SliverAppBar for headers and SliverList or SliverGrid for scrollable content.
dart
CustomScrollView(
slivers: [
SliverAppBar(
title: Text('Title'),
floating: true,
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 20,
),
),
],
)Output
A scrollable screen with a floating app bar and a list of 20 items below it.
Example
This example shows a CustomScrollView with a floating SliverAppBar and a scrollable list of items using SliverList.
dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( title: Text('CustomScrollView Demo'), floating: true, expandedHeight: 150, flexibleSpace: FlexibleSpaceBar( background: Container(color: Colors.blueAccent), ), ), SliverList( delegate: SliverChildBuilderDelegate( (context, index) => ListTile(title: Text('Item $index')), childCount: 30, ), ), ], ), ), ); } }
Output
A screen with a blue expandable app bar that floats when scrolling and a list of 30 scrollable items below.
Common Pitfalls
- Not using slivers inside
CustomScrollViewcauses errors; only sliver widgets are allowed. - Forgetting to provide a delegate to
SliverListorSliverGridresults in empty content. - Using regular widgets instead of slivers inside
CustomScrollViewwill cause layout exceptions.
dart
/* Wrong: Using normal ListView inside CustomScrollView */ CustomScrollView( slivers: [ // ListView(), // This will cause an error ], ) /* Right: Use SliverList with delegate */ CustomScrollView( slivers: [ SliverList( delegate: SliverChildBuilderDelegate( (context, index) => ListTile(title: Text('Item $index')), childCount: 10, ), ), ], )
Quick Reference
- CustomScrollView: Container for slivers to create custom scroll effects.
- SliverAppBar: Scrollable app bar with flexible height and floating behavior.
- SliverList: Scrollable list of widgets using a delegate.
- SliverGrid: Scrollable grid layout.
- Always use sliver widgets inside
CustomScrollView.
Key Takeaways
Use CustomScrollView with sliver widgets to build flexible scrollable layouts.
Only sliver widgets like SliverList or SliverAppBar are allowed inside CustomScrollView.
Provide a delegate to SliverList or SliverGrid to display scrollable content.
Avoid placing regular widgets directly inside CustomScrollView to prevent errors.
SliverAppBar can float and expand for dynamic header effects.