Skip to content

Instantly share code, notes, and snippets.

@orestesgaolin
Last active August 18, 2023 18:25
Show Gist options
  • Save orestesgaolin/6e0f6b4a212e572c7b74e5f301abc71b to your computer and use it in GitHub Desktop.
Save orestesgaolin/6e0f6b4a212e572c7b74e5f301abc71b to your computer and use it in GitHub Desktop.
sticky_header in Flutter
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: CustomScrollView(
slivers: <Widget>[
SliverPersistentHeader(
floating: true,
delegate: SliverAppBarDelegate(
minHeight: 60,
maxHeight: 60,
child: Container(
color: Colors.red,
child: Center(
child: Text('This will hide'),
),
),
),
),
SliverPersistentHeader(
pinned: true,
delegate: SliverAppBarDelegate(
minHeight: 60.0,
maxHeight: 60.0,
child: Container(
color: Theme.of(context).scaffoldBackgroundColor,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8.0,
),
child: Text('This will remain visible',
style: TextStyle(fontSize: 20)),
),
Divider(),
],
),
),
),
),
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
return ListTile(
title: Text('List Tile $index'),
);
}, childCount: 100),
),
],
),
);
}
}
class SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
SliverAppBarDelegate({
required this.minHeight,
required this.maxHeight,
required this.child,
});
final double minHeight;
final double maxHeight;
final Widget child;
@override
double get minExtent => minHeight;
@override
double get maxExtent => math.max(maxHeight, minHeight);
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return SizedBox.expand(child: child);
}
@override
bool shouldRebuild(SliverAppBarDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment