Sticky headers on SliverList

One way is to create a CustomScrollView and pass a SliverAppBar pinned to true and a SliverFixedExtentList object with your Widgets.

Example:

List<Widget> _sliverList(int size, int sliverChildCount) {
    var widgetList = new List<Widget>();
    for (int index = 0; index < size; index++)
      widgetList
        ..add(SliverAppBar(
           title: Text("Title $index"),
           pinned: true,
         ))
        ..add(SliverFixedExtentList(
          itemExtent: 50.0,
          delegate:
              SliverChildBuilderDelegate((BuildContext context, int index) {
                   return Container(
                      alignment: Alignment.center,
                      color: Colors.lightBlue[100 * (index % 9)],
                      child: Text('list item $index'),
                   );
              }, childCount: sliverChildCount),
        ));

   return widgetList;
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Slivers"),
    ),
    body: CustomScrollView(
      slivers: _sliverList(50, 10),
    ),
  );
}

enter image description here


SliverPersistentHeader is the more generic widget behind SliverAppBar that you can use.

SliverPersistentHeader(
    delegate: SectionHeaderDelegate("Section B"),
    pinned: true,
),

And the SectionHeaderDelegate can be implement with something like:

class SectionHeaderDelegate extends SliverPersistentHeaderDelegate {
  final String title;
  final double height;

  SectionHeaderDelegate(this.title, [this.height = 50]);

  @override
  Widget build(context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Theme.of(context).primaryColor,
      alignment: Alignment.center,
      child: Text(title),
    );
  }

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => false;
}

Tags:

Flutter