[Flutter] LayoutBuilderを使ってウィジェットのサイズを取得する

[Flutter] LayoutBuilderを使ってウィジェットのサイズを取得する

2023-09-17 hit count image

Flutterでウィジェットのサイズを取得するためLayoutBuilderを使う方法について説明します。

概要

Flutterでアプリを開発する時、時々ウィジェットのサイズを取得する必要が発生します。今回のブログポストではLayoutBuilderを使ってウィジェットのサイズを取得する方法について説明します。

このブログポストで紹介するソースコードは下記のリンクで確認できます。

LayoutBuilder

LayoutBuilderを使うと特定ウィジェットの幅(Width)と高さ(Height)を取得できます。

ウィジェットのサイズ

特定ウィジェットのサイズを取得するためには次のようにLayoutBuilderウィジェットを当該ウィジェットの親ウィジェットまたはチャイルドウィジェットで使うだけです。

...
floatingActionButton: FloatingActionButton(
  onPressed: _incrementCounter,
  tooltip: 'Increment',
  child: LayoutBuilder(builder: (
    BuildContext context,
    BoxConstraints constraints,
  ) {
    print('FloatingActionButton minWidth: ${constraints.minWidth}');
    print('FloatingActionButton maxWidth: ${constraints.maxWidth}');
    print('FloatingActionButton minHeight: ${constraints.minHeight}');
    print('FloatingActionButton maxHeight: ${constraints.maxHeight}');
    return const Icon(Icons.add);
  }),
),
...

このコードを実行すると次のようにウィジェットのサイズを確認することができます。

flutter: FloatingActionButton minWidth: 0.0
flutter: FloatingActionButton maxWidth: 56.0
flutter: FloatingActionButton minHeight: 0.0
flutter: FloatingActionButton maxHeight: 56.0

bodyサイズ

同じ方法でbodyのサイズを取得することができます。LayoutBuilderを使ってbodyのサイズを取得するコードは次のようになります。

...
body: LayoutBuilder(
  builder: (
    BuildContext context,
    BoxConstraints constraints,
  ) {
    print('body minWidth: ${constraints.minWidth}');
    print('body maxWidth: ${constraints.maxWidth}');
    print('body minHeight: ${constraints.minHeight}');
    print('body maxHeight: ${constraints.maxHeight}');
    return Center(
      ...
    );
  },
),
...

このコードを実行すると次のようにbodyのサイズが確認できます。

flutter: body minWidth: 0.0
flutter: body maxWidth: 393.0
flutter: body minHeight: 0.0
flutter: body maxHeight: 737.0

完了

これでLayoutBuilderを使って特定ウィジェットのサイズを取得する方法について見てみました。特定ウィジェットのサイズが必要な場合、このブログポストを参考してLayoutBuilderを使って見てください。

私のブログが役に立ちましたか?下にコメントを残してください。それは私にとって大きな大きな力になります!

アプリ広報

今見てるブログを作成たDekuが開発したアプリを使ってみてください。
Dekuが開発したアプリはFlutterで開発されています。

興味がある方はアプリをダウンロードしてアプリを使ってくれると本当に助かります。

Posts