Skip to content

Instantly share code, notes, and snippets.

@renanyoy
Created April 30, 2026 00:29
Show Gist options
  • Select an option

  • Save renanyoy/9ba96317fd7bcd15a5c41849492380b6 to your computer and use it in GitHub Desktop.

Select an option

Save renanyoy/9ba96317fd7bcd15a5c41849492380b6 to your computer and use it in GitHub Desktop.
flutter: custom sliver
class FooSliver extends SingleChildRenderObjectWidget {
const FooSliver({super.key, super.child});
@override
RenderObject createRenderObject(BuildContext context) => FooRenderSliver();
}
class BarSliver extends SingleChildRenderObjectWidget {
const BarSliver({super.key, super.child = const Text("Hello from Bar")});
@override
RenderObject createRenderObject(BuildContext context) => FooRenderSliver();
}
class FooRenderSliver extends RenderSliverSingleBoxAdapter {
FooRenderSliver({super.child});
@override
void performLayout() {
/// from [RenderSliverToBoxAdapter]
if (child == null) {
geometry = SliverGeometry.zero;
return;
}
final SliverConstraints constraints = this.constraints;
child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
final double childExtent;
switch (constraints.axis) {
case Axis.horizontal:
childExtent = child!.size.width;
break;
case Axis.vertical:
childExtent = child!.size.height;
break;
}
assert(childExtent != null);
final double paintedChildSize =
calculatePaintOffset(constraints, from: 0.0, to: childExtent);
final double cacheExtent =
calculateCacheOffset(constraints, from: 0.0, to: childExtent);
assert(paintedChildSize.isFinite);
assert(paintedChildSize >= 0.0);
geometry = SliverGeometry(
scrollExtent: childExtent,
paintExtent: paintedChildSize,
cacheExtent: cacheExtent,
maxPaintExtent: childExtent,
hitTestExtent: paintedChildSize,
hasVisualOverflow: childExtent > constraints.remainingPaintExtent ||
constraints.scrollOffset > 0.0,
);
setChildParentData(child!, constraints, geometry!);
}
}
CustomScrollView(
slivers: [
FooSliver(
child: Text("Hi From Foo sliver"),
),
BarSliver()
],
),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment