LayoutBuilder class
親ウィジェットのサイズを参考にして、自分自身を決定するようなウィジェットツリーを構築したい時にLayoutBuilderウィジェットを使います。
フレームワークが、レイアウト時にbuilderプロパティに設定されたコールバックを呼び出し、親ウィジェットの制約を提供することを除いて、Builderウィジェットに似ています。
これは、親が子のサイズを制約し、子の固有のサイズに依存しない場合に役立ちます。LayoutBuilderの最終的なサイズは、その子のサイズと一致します。
builderプロパティに設定されたコールバックは次のような状況で呼び出されます。
- 初めてウィジェットがレイアウトされる時
- 親ウィジェットが今までとは違うレイアウトconstraints(制約)を渡してきた時
- 親ウィジェットがこのウィジェットをアップデートする時(リビルド時と思われる。)
- Builder関数がサブスクライブする依存関係が変更されたとき。
工事中🏗
親が同じ制約を繰り返し渡す場合、レイアウト中にbuilder関数は呼び出されません。
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); /// This is the main application widget. class MyApp extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatelessWidget(), ); } } /// This is the stateless widget that the main application instantiates. class MyStatelessWidget extends StatelessWidget { MyStatelessWidget({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("LayoutBuilder Example")), body: LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth > 600) { return _buildWideContainers(); } else { return _buildNormalContainer(); } }, ), ); } Widget _buildNormalContainer() { return Center( child: Container( height: 100.0, width: 100.0, color: Colors.red, ), ); } Widget _buildWideContainers() { return Center( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Container( height: 100.0, width: 100.0, color: Colors.red, ), Container( height: 100.0, width: 100.0, color: Colors.yellow, ), ], ), ); } }
向きを変えると表示が変わる。
スマホの向き(縦向き、横向き)によって表示を変えるウィジェットとしてOrientationBuilderウィジェットもあります。
2021/2/10 Update the UI based on orientationの訳
をご覧ください。
以下のリソースもご覧ください。
- SliverLayoutBuilder, the sliver counterpart of this widget.
- Builder, which calls a
builder
function at build time. - StatefulBuilder, which passes its
builder
function asetState
callback. - CustomSingleChildLayout, which positions its child during layout.
- The catalog of layout widgets.
参考
https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html