世界最大級のオンライン学習サービス「Udemy」のセール状況はこちら

【Flutter】LimitedBoxの使い方|親が範囲無限の場合のみ子に最大値を設定する

親ウィジェットの範囲が無限の場合にListViewなどの子ウィジェットのサイズ調整するにはどうするの?

こんな時に便利なのが LimitedBox ウィジェットです。

LimitedBoxを使用することで親ウィジェットの範囲が無限の場合でもListViewなど親の範囲に大きさが依存するウィジェットの最大値を設定できます。

それではLimitedBoxの基本的な使い方と似た性質を持つSizedBoxとの違いについて解説していきます!

目次

基本的な使い方

LimitedBoxの基本的な使い方について解説します。

LimitedBoxのchildプロパティの引数に最大値を設定したいウィジェットを渡し、maxHeightプロパティで高さの最大値、maxWidthプロパティで横幅の最大値を設定できます。

またLimitedBoxの性質についてですが、LimitedBoxのサイズ調整が有効になるのは親ウィジェットがColumnやRowのように範囲が無限の場合のみで、親ウィジェットがContainerなどのように範囲が定まっている場合は無効化されます。

LimitedBox(
  maxHeight: 250,
  child: ListView.builder(
    itemCount: 30,
    itemBuilder: (BuildContext context, int index) {
      return Center(
        child: Text("Hello World"),
      );
    },
  ),
),
画像のサンプルコード
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            "Top",
            style: TextStyle(fontSize: 30),
          ),
          LimitedBox(
            maxHeight: 250,
            child: Container(
              color: Colors.amber,
              child: ListView.builder(
                itemCount: 30,
                itemBuilder: (BuildContext context, int index) {
                  return Center(
                    child: Text(
                      "Hello World",
                      style: TextStyle(
                        fontSize: 30,
                        height: 2,
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
          Text(
            "Bottom",
            style: TextStyle(fontSize: 30),
          ),
        ],
      ),
    );
  }
}

LimitedBox と SizedBox の違い

ここでLimitedBoxと似た性質を持つSizedBoxとの違いついて解説します。

1つ目の違い:LimitedBoxでは親ウィジェットの範囲が無限の場合のみ有効で親の範囲が定まっている場合には無効化されるのに対し、SizedBoxでは親ウィジェットの範囲に左右されず子ウィジェットのサイズを調整できます。

2つ目の違い:LimitedBoxの子ウィジェットのサイズがmaxHeighまたはmaxWidthプロパティで設定してサイズよりも小さい場合には元のサイズが使用されるのに対し、SizedBoxではheightとwidthプロパティで設定したサイズが強制的に使用されます。

まとめ

今回はLimitedBoxの基本的な使い方とSizedBoxとの違いについて解説しました。

LimitedBoxを使用することで親ウィジェットの範囲が無限の場合でもListViewなど親の範囲に大きさが依存するウィジェットの最大値を設定できるのでぜひ使ってみてください。

目次