Created
November 26, 2022 16:54
-
-
Save RyouMon/f7e4b78fed64d304dd675c366433ed2a to your computer and use it in GitHub Desktop.
Flutter: LayoutBuilder Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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