Flutter中无需第三方包实现ListView粘性头部的方法
无需第三方包实现Flutter粘性头部效果
可以通过Flutter原生的CustomScrollView结合SliverPersistentHeader组件来实现你需要的粘性头部效果,完全不需要依赖第三方库。以下是对应的实现代码:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( leading: IconButton( icon: const Icon( Icons.arrow_back_ios, size: 16, ), onPressed: () { Navigator.of(context).pop(); }, ), title: const Text('Results'), ), body: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: [ // 1-10的列表项 SliverList( delegate: SliverChildBuilderDelegate( (context, index) { return ListTile( leading: Text('${index + 1}'), ); }, childCount: 10, ), ), // 粘性头部 SliverPersistentHeader( pinned: true, delegate: _StickyHeaderDelegate( title: 'Next', backgroundColor: Colors.blue, ), ), // 11-20的列表项 SliverList( delegate: SliverChildBuilderDelegate( (context, index) { return ListTile( leading: Text('${index + 11}'), ); }, childCount: 10, ), ), ], ), ), ); } } // 自定义粘性头部代理类 class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate { final String title; final Color backgroundColor; _StickyHeaderDelegate({required this.title, required this.backgroundColor}); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Container( width: double.infinity, padding: const EdgeInsets.all(20), alignment: Alignment.center, color: backgroundColor, child: Text( title, style: const TextStyle(color: Colors.white, fontSize: 16), ), ); } @override double get maxExtent => 60; // 头部展开时的高度 @override double get minExtent => 60; // 头部固定时的高度(和max一致保持高度不变) @override bool shouldRebuild(covariant _StickyHeaderDelegate oldDelegate) { return title != oldDelegate.title || backgroundColor != oldDelegate.backgroundColor; } }
关键部分说明:
- CustomScrollView:作为滚动容器,支持多种Sliver类型组件,是实现复杂滚动效果的原生方案。
- SliverPersistentHeader:通过
pinned: true设置头部固定在顶部,需要配合自定义的SliverPersistentHeaderDelegate来定义头部的样式和尺寸。 - SliverList:用来包裹普通的列表项,替代原来的
SingleChildScrollView+Column的组合,更适合和Sliver系列组件配合使用。
内容的提问来源于stack exchange,提问作者dipansh
相关产品推荐
相关产品推荐

