Skip to content

Instantly share code, notes, and snippets.

@lopo12123
Last active July 29, 2024 15:18
Show Gist options
  • Save lopo12123/fa2d412f12dff1c555853c60b49ff22f to your computer and use it in GitHub Desktop.
Save lopo12123/fa2d412f12dff1c555853c60b49ff22f to your computer and use it in GitHub Desktop.
BadFL Example Code (extension/iterable)
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
// switch to try example1 & example2
home: Example1(),
// home: Example2(),
);
}
}
class Example1 extends StatelessWidget {
const Example1({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
// mark as `List<Widget>` to use `slotted` with default builder (asIs)
children: const <Widget>[
Text('item1'),
Text('item2'),
Text('item3'),
Text('item4'),
].slotted(slot: const Divider()),
),
);
}
}
class Example2 extends StatelessWidget {
const Example2({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
// custom builder for widget creation
children: const [1, 2, 3, 4].slotted(
builder: (int num) => Text('item$num'),
slot: const Divider(),
),
),
);
}
}
// Since Dartpad does not support importing packages,
// I need to copy the necessary code here.
// You can directly use `import "package:bad_fl/bad_fl.dart"` to import it when using it
extension IterableExt<Item> on Iterable<Item> {
List<Product> slotted<Product>({
required Product Function(Item item) builder,
required Product slot,
}) {
final result = <Product>[];
bool skip = true;
for (Item item in this) {
if (skip) {
skip = false;
} else {
result.add(slot);
}
result.add(builder(item));
}
return result;
}
}
Widget asIs(Widget it) => it;
extension IterableWidgetExt on Iterable<Widget> {
List<Widget> slotted({
Widget Function(Widget item) builder = asIs,
required Widget slot,
}) {
final result = <Widget>[];
bool skip = true;
for (Widget item in this) {
if (skip) {
skip = false;
} else {
result.add(slot);
}
result.add(builder(item));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment