Flutter: List and Scrolling
Scrolling is the most natural interaction on mobile — if your list isn't smooth, users will swipe toward the uninstall button.
📋 Prerequisites: You need to master the following first
- Lesson 6: Material Design & Common Widgets
1. What You Will Learn
- ListView.builder / ListView.separated lazy loading and itemExtent performance optimization
- GridView.builder / SliverGrid large data grid rendering
- ScrollController: scroll listening, scroll-to-top, pull-to-load-more
- Sliver family: SliverAppBar, SliverList, SliverPersistentHeader
- ShopApp million-level product list + pull-to-refresh + infinite scrolling
2. A True Story of a Laggy List
(1) Pain Point: The 30fps Nightmare of a Million-Product List
Bob's ShopApp has millions of product records. He uses ListView(children: allProducts.map(...).toList()) to create all widgets at once — 100 items drops to 30fps, 1000 items causes an OOM crash. Worse, users must manually tap "Load More" at the bottom, resulting in a 60% bounce rate.
(2) The Lazy Loading + Infinite Scrolling Solution
ListView.builder only builds visible items — even with 10 million records, it only renders the 10-20 items visible on screen. Combined with ScrollController to monitor scroll position, it automatically triggers loading more data.
import 'package:flutter/material.dart';
// Simplified class definition
class Product {
final String name;
final double price;
const Product({required this.name, required this.price});
}
// Lazy loading: only builds visible items
ListView.builder(
itemCount: products.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index == products.length) return const LoadingIndicator();
return ProductTile(product: products[index]);
},
)
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
(3) Benefit: 60fps + Seamless Loading
After switching to builder lazy loading + infinite scrolling, Bob's million-product list runs at a stable 60fps, and the bounce rate drops from 60% to 15%.
3. The ListView System
graph TD
SV[ScrollView] --> LV[ListView]
SV --> GV2[GridView]
SV --> CS[CustomScrollView]
CS --> SA[SliverAppBar]
CS --> SL[SliverList]
CS --> SG[SliverGrid]
CS --> SPH[SliverPersistentHeader]
LV --> |builder| Lazy[Lazy Loading]
LV --> |controller| LoadMore[Load More]
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
(1) ListView Construction Methods
| Constructor | itemCount | Build Timing | Use Case |
|---|---|---|---|
ListView(children:) |
Fixed | Build all at once | Few items (<20) |
ListView.builder() |
Variable | Lazy load visible items | Large data lists |
ListView.separated() |
Variable | Lazy load + separators | Lists with dividers |
ListView.custom() |
Variable | Custom SliverChildDelegate | Special requirements |
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Product list (ListView.builder)
import 'package:flutter/material.dart';
// Simplified class definition
class Product {
final String name;
final double price;
final int id;
const Product({required this.name, required this.price, required this.id});
}
// Simplified API class
class ProductApi {
Future<List<Product>> fetchProducts({int page = 1}) async {
await Future.delayed(const Duration(milliseconds: 500));
return List.generate(20, (i) => Product(
name: 'Product ${(page - 1) * 20 + i + 1}',
price: 9.99 + i * 5,
id: (page - 1) * 20 + i + 1,
));
}
}
final api = ProductApi();
class ProductListPage extends StatefulWidget {
const ProductListPage({super.key});
@override
State<ProductListPage> createState() => _ProductListPageState();
}
class _ProductListPageState extends State<ProductListPage> {
final ScrollController _controller = ScrollController();
List<Product> _products = [];
bool _isLoading = false;
bool _hasMore = true;
int _page = 1;
@override
void initState() {
super.initState();
_loadProducts();
_controller.addListener(_onScroll);
}
void _onScroll() {
if (_controller.position.pixels >= _controller.position.maxScrollExtent - 200) {
_loadProducts(); // Load more when near bottom
}
}
Future<void> _loadProducts() async {
if (_isLoading || !_hasMore) return;
setState(() => _isLoading = true);
final newProducts = await api.fetchProducts(page: _page++);
setState(() {
_products.addAll(newProducts);
_isLoading = false;
_hasMore = newProducts.length >= 20;
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: () async {
_page = 1;
_products.clear();
_hasMore = true;
await _loadProducts();
},
child: ListView.builder(
controller: _controller,
itemCount: _products.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index == _products.length) {
return const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
);
}
return ProductListTile(product: _products[index]);
},
),
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: List with dividers (ListView.separated)
import 'package:flutter/material.dart';
// Simplified class definition
class Order {
final int id;
final double total;
final List<String> items;
final String status;
const Order({required this.id, required this.total, required this.items, required this.status});
}
Widget _buildStatusChip(String status) => Chip(label: Text(status));
ListView.separated(
itemCount: orders.length,
separatorBuilder: (context, index) => const Divider(height: 1, indent: 72),
itemBuilder: (context, index) {
final order = orders[index];
return ListTile(
leading: CircleAvatar(child: Text('#${order.id}')),
title: Text('Order #${order.id}'),
subtitle: Text('\$${order.total.toStringAsFixed(2)} • ${order.items.length} items'),
trailing: _buildStatusChip(order.status),
);
},
)
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
4. Performance Optimization
(1) itemExtent and prototypeItem
| Optimization | Effect | Improvement |
|---|---|---|
itemExtent |
Fixed item height, skip measurement | Scrolling performance +30% |
prototypeItem |
Measure reference item once | When all items have uniform height |
const constructors |
Reuse widget instances | Reduces rebuild overhead |
addAutomaticKeepAlives |
Control caching policy | Memory optimization |
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: itemExtent optimization
import 'package:flutter/material.dart';
// Fixed-height items: use itemExtent for maximum performance
ListView.builder(
itemExtent: 72, // Each item is exactly 72 pixels tall
itemCount: 10000,
itemBuilder: (context, index) => ListTile(
title: Text('Product ${index + 1}'),
trailing: Text('\$${(9.99 + index * 5).toStringAsFixed(2)}'),
),
)
// Variable-height items: use prototypeItem
ListView.builder(
prototypeItem: const ListTile(title: Text('Prototype'), trailing: Text('\$0.00')),
itemCount: products.length,
itemBuilder: (context, index) => ProductListTile(product: products[index]),
)
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
5. ScrollController Advanced Control
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: Scroll-to-top button
import 'package:flutter/material.dart';
class ScrollToTopList extends StatefulWidget {
const ScrollToTopList({super.key});
@override
State<ScrollToTopList> createState() => _ScrollToTopListState();
}
class _ScrollToTopListState extends State<ScrollToTopList> {
final _controller = ScrollController();
bool _showTopButton = false;
@override
void initState() {
super.initState();
_controller.addListener(() {
final show = _controller.offset > 500;
if (show != _showTopButton) setState(() => _showTopButton = show);
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: _controller,
itemCount: 5000,
itemBuilder: (_, i) => ListTile(title: Text('Item \$i')),
),
floatingActionButton: _showTopButton
? FloatingActionButton.mini(
onPressed: () => _controller.animateTo(0,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut),
child: const Icon(Icons.arrow_upward),
)
: null,
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
6. Sliver Advanced Scrolling
Slivers are building blocks of CustomScrollView that can be combined to create complex scrolling effects.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: CustomScrollView + SliverAppBar
import 'package:flutter/material.dart';
// Simplified class definitions
class Product {
final String name;
const Product({required this.name});
}
class ProductCard extends StatelessWidget {
final Product product;
const ProductCard({super.key, required this.product});
@override Widget build(BuildContext context) => Card(child: Text(product.name));
}
final categories = ['All', 'Electronics', 'Clothing', 'Home'];
final products = List.generate(20, (i) => Product(name: 'Product ${i + 1}'));
const _hasMore = true;
class LoadingIndicator extends StatelessWidget {
const LoadingIndicator({super.key});
@override Widget build(BuildContext context) => const Padding(
padding: EdgeInsets.all(16), child: Center(child: CircularProgressIndicator()));
}
CustomScrollView(
slivers: [
// Collapsible header
SliverAppBar(
expandedHeight: 200,
floating: true,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
title: const Text('Flash Sale'),
background: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(colors: [Colors.blue, Colors.purple]),
),
child: const Center(child: Text('UP TO 50% OFF',
style: TextStyle(fontSize: 32, color: Colors.white, fontWeight: FontWeight.bold))),
),
),
),
// Category chips (fixed height)
SliverToBoxAdapter(
child: SizedBox(
height: 50,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
children: categories.map((c) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Chip(label: Text(c)),
)).toList(),
),
),
),
// Product grid
SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverGrid.extent(
maxCrossAxisExtent: 180,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
children: products.map((p) => ProductCard(product: p)).toList(),
),
),
// Loading indicator at bottom
SliverToBoxAdapter(
child: _hasMore ? const LoadingIndicator() : const SizedBox(height: 40),
),
],
)
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
▶ Example
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
: SliverPersistentHeader sticky category header
import 'package:flutter/material.dart';
class StickyCategoryHeader extends SliverPersistentHeaderDelegate {
final String category;
StickyCategoryHeader(this.category);
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(
color: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
alignment: Alignment.centerLeft,
child: Text(category, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
);
}
@override
double get maxExtent => 40;
@override
double get minExtent => 40;
@override
bool shouldRebuild(covariant StickyCategoryHeader oldDelegate) =>
oldDelegate.category != category;
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
7. Complete Example: ShopApp Infinite Scrolling Product List
import 'package:flutter/material.dart';
// Simplified class definitions
class Product {
final int id;
final String name;
final double price;
const Product({required this.id, required this.name, required this.price});
}
class ProductCard extends StatelessWidget {
final Product product;
const ProductCard({super.key, required this.product});
@override Widget build(BuildContext context) => Card(child: Padding(
padding: const EdgeInsets.all(8), child: Text('${product.name} \$${product.price}')));
}
class MockProducts {
static List<Product> generate({int count = 20, int offset = 0, String category = 'All'}) {
return List.generate(count, (i) => Product(
id: offset + i + 1,
name: 'Product ${offset + i + 1}',
price: (9.99 + (offset + i) * 5).toDouble(),
));
}
}
class InfiniteProductList extends StatefulWidget {
const InfiniteProductList({super.key});
@override
State<InfiniteProductList> createState() => _InfiniteProductListState();
}
class _InfiniteProductListState extends State<InfiniteProductList> {
final _controller = ScrollController();
final List<Product> _products = [];
bool _isLoading = false;
bool _hasMore = true;
int _page = 0;
String _category = 'All';
@override
void initState() {
super.initState();
_loadMore();
_controller.addListener(() {
if (_controller.position.pixels >= _controller.position.maxScrollExtent - 300 && !_isLoading && _hasMore) {
_loadMore();
}
});
}
Future<void> _loadMore() async {
if (_isLoading) return;
setState(() => _isLoading = true);
await Future.delayed(const Duration(seconds: 1)); // Simulate API
final newItems = MockProducts.generate(count: 20, offset: _page * 20, category: _category);
setState(() {
_products.addAll(newItems);
_page++;
_isLoading = false;
_hasMore = _page < 500; // Max 10,000 items for demo
});
}
Future<void> _refresh() async {
setState(() { _page = 0; _products.clear(); _hasMore = true; });
await _loadMore();
}
@override
void dispose() { _controller.dispose(); super.dispose(); }
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Products')),
body: RefreshIndicator(
onRefresh: _refresh,
child: CustomScrollView(
controller: _controller,
slivers: [
SliverToBoxAdapter(
child: SizedBox(height: 48, child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
children: ['All', 'Electronics', 'Clothing', 'Home'].map((c) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: ChoiceChip(label: Text(c), selected: c == _category,
onSelected: (_) => setState(() { _category = c; _refresh(); })),
)).toList(),
)),
),
SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverGrid.extent(
maxCrossAxisExtent: 180,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
children: _products.map((p) => ProductCard(
key: ValueKey(p.id), product: p,
)).toList(),
),
),
if (_isLoading) const SliverToBoxAdapter(
child: Padding(padding: EdgeInsets.all(16), child: Center(child: CircularProgressIndicator())),
),
if (!_hasMore) const SliverToBoxAdapter(
child: Padding(padding: EdgeInsets.all(16), child: Center(child: Text('No more products'))),
),
],
),
),
);
}
}
> Output: Run on a local Flutter SDK (Flutter 3.x / Dart 3.x). The Piston server does not have Flutter installed — use `flutter run` on your local machine for hands-on comparison. Actual UI/state may vary slightly by platform.
❓ FAQ
shrinkWrap: true and physics: NeverScrollableScrollPhysics(). However, this hurts performance — consider using Slivers instead.flutter_staggered_grid_view package's MasonryGridView.builder. Standard Flutter doesn't include a staggered grid.📖 Summary
- ListView.builder lazy loads, only building visible items, supporting million-level data
- itemExtent fixes item height, skipping measurement, improving scrolling performance by 30%+
- ScrollController monitors scrolling, controls scroll-to-top, and triggers load-more
- RefreshIndicator implements pull-to-refresh
- CustomScrollView + Sliver combinations create complex scrolling effects
📝 Exercises
- Basic (⭐): Create a 100-item ListView.builder, each item showing product name and price, with fixed itemExtent.
- Intermediate (⭐⭐): Implement pull-to-refresh + auto load-more on scroll to bottom, showing CircularProgressIndicator while loading.
- Challenge (⭐⭐⭐): Use CustomScrollView + SliverAppBar + SliverGrid to build a home page: collapsible header + category tags + product grid + scroll-to-load-more.