Flutter: 列表与滚动

滚动是移动端最自然的交互——你的列表不流畅,用户的手指就会滑向卸载按钮。

📋 前置知识:需要先掌握以下内容

1. 你将学到


2. 一个列表卡顿的真实故事

(1) 痛点:千万商品列表的 30fps 噩梦

Bob 的 ShopApp 有千万级商品数据。他用 ListView(children: allProducts.map(...).toList()) 一次性创建所有 Widget,100 个商品就卡到 30fps,1000 个直接 OOM 崩溃。更糟的是,每次滚动到底部需要手动点"加载更多",用户跳出率 60%。

(2) 懒加载 + 无限滚动的解法

ListView.builder 只构建可见项,1000 万条数据也只渲染屏幕上可见的 10-20 项。配合 ScrollController 监听滚动位置,自动触发加载更多。

DART
import 'package:flutter/material.dart';

// 简化类定义
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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

(3) 收益:60fps + 无感加载

Bob 改用 builder 懒加载 + 无限滚动后,千万商品列表稳定 60fps,跳出率从 60% 降到 15%。


3. ListView 体系

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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

(1) ListView 构造方式

构造方式 itemCount 构建时机 适用场景
ListView(children:) 固定 一次性全部构建 少量项(<20)
ListView.builder() 可变 懒加载可见项 大数据列表
ListView.separated() 可变 懒加载 + 分隔符 带分隔线列表
ListView.custom() 可变 自定义 SliverChildDelegate 特殊需求

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:商品列表(ListView.builder)

DART
import 'package:flutter/material.dart';

// 简化类定义
class Product {
  final String name;
  final double price;
  final int id;
  const Product({required this.name, required this.price, required this.id});
}

// 简化API类
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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:带分隔线的列表(ListView.separated)

DART
import 'package:flutter/material.dart';

// 简化类定义
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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

4. 性能优化

(1) itemExtent 与 prototypeItem

优化项 作用 提升幅度
itemExtent 固定项高度,跳过测量 滚动性能 +30%
prototypeItem 参考项测量一次 项高度统一时
const 构造 复用 Widget 实例 减少重建开销
addAutomaticKeepAlives 控制缓存策略 内存优化

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:itemExtent 优化

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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

5. ScrollController 高级控制

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:回到顶部按钮

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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

6. Sliver 高级滚动

Sliver 是 CustomScrollView 的子块,可组合实现复杂滚动效果。

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:CustomScrollView + SliverAppBar

DART
import 'package:flutter/material.dart';

// 简化类定义
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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

▶ 示例

TEXT 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

:SliverPersistentHeader 粘性分类头

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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

7. 完整示例:ShopApp 无限滚动商品列表

DART
import 'package:flutter/material.dart';

// 简化类定义
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 📖 仅展示
> **输出:** 在本地 Flutter SDK(Flutter 3.x / Dart 3.x)运行。Piston 服务器未安装 Flutter,请在本机 `flutter run` 实操对照。实际 UI/状态会因平台略有差异。

❓ 常见问题

Q ListView 和 SingleChildScrollView 有什么区别?
A ListView 懒加载适合列表;SingleChildScrollView 一次性构建全部子组件,适合少量内容的长页面。
Q ListView 嵌套 ListView 报错怎么办?
A 内层 ListView 设置 shrinkWrap: truephysics: NeverScrollableScrollPhysics()。但性能差,建议用 Sliver 替代。
Q RefreshIndicator 不生效?
A 子组件必须是可滚动的(ListView/GridView/CustomScrollView),且内容需超出视口高度。
Q ScrollController 的 maxScrollExtent 是 0?
A 内容未超出视口时 maxScrollExtent 为 0。确保列表足够长,或在 WidgetsBinding.instance.addPostFrameCallback 中读取。
Q SliverAppBar 的 floating 和 snap 有什么区别?
A floating=true 向下滚动时立即显示;snap=true 松手时自动完全展开(需配合 floating)。
Q 如何实现瀑布流(StaggeredGrid)?
A 使用 flutter_staggered_grid_view 包的 MasonryGridView.builder,标准 Flutter 不自带瀑布流。

📖 小节


📝 作业

  1. 基础题(难度⭐):创建一个 100 项的 ListView.builder,每项显示商品名和价格,固定 itemExtent。
  2. 进阶题(难度⭐⭐):实现下拉刷新 + 滚动到底部自动加载更多,加载时显示 CircularProgressIndicator。
  3. 挑战题(难度⭐⭐⭐):用 CustomScrollView + SliverAppBar + SliverGrid 构建首页:可折叠头部 + 分类标签 + 商品网格 + 滚动加载更多。

← 上一课 | 下一课 →

Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

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

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