Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save TesteurManiak/e478318e74333e0c981f9b94188508ab to your computer and use it in GitHub Desktop.

Select an option

Save TesteurManiak/e478318e74333e0c981f9b94188508ab to your computer and use it in GitHub Desktop.
Showcase of SliverSeparatedChildBuilderDelegate
import 'dart:math' as math;
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
final elements = List<int>.generate(100, (i) => i);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: CustomScrollView(
slivers: [
SliverList(
delegate: SliverSeparatedChildBuilderDelegate(
builder: builder,
separatorBuilder: separatorBuilder,
childCount: elements.length,
),
),
],
),
),
);
}
Widget builder(BuildContext context, int index) {
final element = elements[index];
return ListTile(
title: Text('$element'),
);
}
Widget separatorBuilder(BuildContext context, int index) => Container(
width: double.maxFinite,
height: 16,
color: Colors.orange,
);
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
);
}
}
class SliverSeparatedChildBuilderDelegate extends SliverChildBuilderDelegate {
SliverSeparatedChildBuilderDelegate({
required NullableIndexedWidgetBuilder builder,
required IndexedWidgetBuilder separatorBuilder,
required int childCount,
}) : super(
(context, index) => _separatedBuilder(
context,
index,
builder,
separatorBuilder,
),
childCount: math.max(0, childCount * 2 - 1),
semanticIndexCallback: _separatedSemanticIndexCallback,
);
static int? _separatedSemanticIndexCallback(Widget _, int localIndex) {
if (localIndex.isEven) {
return localIndex ~/ 2;
}
return null;
}
static Widget? _separatedBuilder(
BuildContext context,
int index,
NullableIndexedWidgetBuilder builder,
IndexedWidgetBuilder separatorBuilder,
) {
final int itemIndex = index ~/ 2;
if (index.isEven) {
return builder(context, itemIndex);
}
return separatorBuilder(context, itemIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment