Skip to content

Instantly share code, notes, and snippets.

@slightfoot
Created September 11, 2024 17:45
Show Gist options
  • Save slightfoot/2e956ab9f5c3529ae1f30a3717815613 to your computer and use it in GitHub Desktop.
Save slightfoot/2e956ab9f5c3529ae1f30a3717815613 to your computer and use it in GitHub Desktop.
Max Cross Axis Wrap Example - by Simon Lightfoot - Humpday Q&A :: 11th September 2024 #Flutter #Dart - https://www.youtube.com/watch?v=LbpboHb49PM
import 'package:flutter/material.dart';
void main() {
runApp(const WrapApp());
}
class WrapApp extends StatelessWidget {
const WrapApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: const Home(),
);
}
}
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: MaxCrossAxisWrap(
maxCrossAxisExtent: 300.0,
crossAxisAlignment: WrapCrossAlignment.end,
children: [
for (int i = 0; i < 42; i++) //
Builder(
builder: (BuildContext context) {
if (i % 3 == 0) {
return const SizedBox(
height: 200.0,
child: Tile(),
);
}
return const Tile();
},
),
],
),
);
}
}
class MaxCrossAxisWrap extends StatelessWidget {
const MaxCrossAxisWrap({
super.key,
this.direction = Axis.horizontal,
this.alignment = WrapAlignment.start,
this.spacing = 0.0,
this.runAlignment = WrapAlignment.start,
this.runSpacing = 0.0,
this.crossAxisAlignment = WrapCrossAlignment.start,
required this.maxCrossAxisExtent,
required this.children,
});
final Axis direction;
final WrapAlignment alignment;
final double spacing;
final WrapAlignment runAlignment;
final double runSpacing;
final WrapCrossAlignment crossAxisAlignment;
final double maxCrossAxisExtent;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final columnCount = constraints.maxWidth ~/ maxCrossAxisExtent;
final remainingWidth = constraints.maxWidth % maxCrossAxisExtent;
final childWidth = maxCrossAxisExtent + (remainingWidth / columnCount);
return Wrap(
direction: direction,
alignment: alignment,
spacing: spacing,
runAlignment: runAlignment,
runSpacing: runSpacing,
crossAxisAlignment: crossAxisAlignment,
children: [
for (final child in children) //
SizedBox(
width: childWidth,
child: child,
),
],
);
},
);
}
}
class Tile extends StatelessWidget {
const Tile({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(8.0),
child: const ListTile(
textColor: Colors.black,
iconColor: Colors.black,
leading: Icon(Icons.tag_faces),
trailing: Icon(Icons.favorite),
title: Text('Lorem Ipsum is simply dummy text'),
subtitle: Text('Lorem Ipsum has been the industry\'s standard'),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment