Skip to content

Instantly share code, notes, and snippets.

@RyouMon
Created November 26, 2022 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyouMon/f7e4b78fed64d304dd675c366433ed2a to your computer and use it in GitHub Desktop.
Save RyouMon/f7e4b78fed64d304dd675c366433ed2a to your computer and use it in GitHub Desktop.
Flutter: LayoutBuilder Example
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class ResponsiveColumn extends StatelessWidget {
const ResponsiveColumn({super.key, required this.children});
final List<Widget> children;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (constraints.maxWidth < 200) {
return Column(
mainAxisSize: MainAxisSize.min,
children: children,
);
} else {
var children_ = <Widget>[];
for (var i = 0; i < children.length; i += 2) {
if (i + 1 < children.length) {
children_.add(Row(
mainAxisSize: MainAxisSize.min,
children: [children[i], children[i + 1]],
));
} else {
children_.add(children[i]);
}
}
return Column(
mainAxisSize: MainAxisSize.min,
children: children_,
);
}
},
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
var children = List.filled(6, const Text("A"));
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Column(
children: [
SizedBox(
width: 190,
child: ResponsiveColumn(children: children),
),
ResponsiveColumn(children: children),
],
)));
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'LayoutBuilder Example'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment