Skip to content

Instantly share code, notes, and snippets.

@AnthonyDS
Last active January 25, 2023 06:44
Show Gist options
  • Save AnthonyDS/78ed3794802c2ef7697c5f0358cdee79 to your computer and use it in GitHub Desktop.
Save AnthonyDS/78ed3794802c2ef7697c5f0358cdee79 to your computer and use it in GitHub Desktop.
Flutter CustomMultiChildLayout

Flutter CustomMultiChildLayout

Created with <3 with dartpad.dev.

///
/// docs: https://api.flutter.dev/flutter/widgets/CustomMultiChildLayout-class.html
///
import 'package:flutter/material.dart';
void main() => runApp(const ExampleApp());
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Scaffold(
body: ExampleWidget(),
),
),
);
}
}
class _CascadeLayoutDelegate extends MultiChildLayoutDelegate {
final Map<String, Color> colors;
int column = 0;
int row = 0;
final int maxColumn = 3;
_CascadeLayoutDelegate({
required this.colors,
});
@override
void performLayout(Size size) {
final double columnWidth = size.width / colors.length;
Offset childPosition = Offset.zero;
for (final String color in colors.keys) {
final Size currentSize = layoutChild(
color,
BoxConstraints(maxHeight: size.height, maxWidth: columnWidth),
);
childPosition = Offset(
(currentSize.width + 4) * column,
(currentSize.height + 4) * row,
);
positionChild(color, childPosition);
if(column < (maxColumn - 1)) {
column++;
} else {
row++;
column = 0;
}
}
}
@override
bool shouldRelayout(_CascadeLayoutDelegate oldDelegate) {
return true;
}
}
class ExampleWidget extends StatelessWidget {
const ExampleWidget({super.key});
static const Map<String, Color> _colors = <String, Color>{
'Red': Colors.red,
'Green': Colors.green,
'Blue': Colors.blue,
'Cyan': Colors.cyan,
'Yellow': Colors.yellow,
'Orange': Colors.orange,
'Grey': Colors.grey,
};
@override
Widget build(BuildContext context) {
return CustomMultiChildLayout(
delegate: _CascadeLayoutDelegate(
colors: _colors,
),
children: <Widget>[
// Create all of the colored boxes in the colors map.
for (MapEntry<String, Color> entry in _colors.entries)
// The "id" can be any Object, not just a String.
LayoutId(
id: entry.key,
child: Container(
color: entry.value,
width: 100.0,
height: 100.0,
alignment: Alignment.center,
child: Text(
entry.key,
style: const TextStyle(
color: Colors.white,
shadows: [
Shadow(blurRadius: 1, color: Colors.black, offset: Offset(0, 0)),
],
),
),
),
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment