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

1. What You Will Learn


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.

DART
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]);
  },
)
TEXT
> 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

100%
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]
TEXT
> 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

TEXT
> 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)

DART
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]);
        },
      ),
    );
  }
}
TEXT
> 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

TEXT
> 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)

DART
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),
    );
  },
)
TEXT
> 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

TEXT
> 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

DART
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]),
)
TEXT
> 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

TEXT
> 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

DART
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,
    );
  }
}
TEXT
> 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

TEXT
> 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

DART
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),
    ),
  ],
)
TEXT
> 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

TEXT
> 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

DART
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;
}
TEXT
> 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

DART
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'))),
            ),
          ],
        ),
      ),
    );
  }
}
TEXT
> 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

Q What's the difference between ListView and SingleChildScrollView?
A ListView lazy loads for lists; SingleChildScrollView builds all children at once, suitable for long pages with little content.
Q ListView nested inside ListView throws an error?
A Set the inner ListView to shrinkWrap: true and physics: NeverScrollableScrollPhysics(). However, this hurts performance — consider using Slivers instead.
Q RefreshIndicator not working?
A The child must be scrollable (ListView/GridView/CustomScrollView), and the content must exceed the viewport height.
Q ScrollController's maxScrollExtent is 0?
A maxScrollExtent is 0 when content doesn't exceed the viewport. Ensure the list is long enough, or read it in WidgetsBinding.instance.addPostFrameCallback.
Q What's the difference between SliverAppBar's floating and snap?
A floating=true shows it immediately on scroll down; snap=true auto-expands fully on release (requires floating).
Q How to implement a staggered grid (MasonryGrid)?
A Use the flutter_staggered_grid_view package's MasonryGridView.builder. Standard Flutter doesn't include a staggered grid.

📖 Summary


📝 Exercises

  1. Basic (⭐): Create a 100-item ListView.builder, each item showing product name and price, with fixed itemExtent.
  2. Intermediate (⭐⭐): Implement pull-to-refresh + auto load-more on scroll to bottom, showing CircularProgressIndicator while loading.
  3. Challenge (⭐⭐⭐): Use CustomScrollView + SliverAppBar + SliverGrid to build a home page: collapsible header + category tags + product grid + scroll-to-load-more.

← Previous Lesson | Next Lesson →

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏