Menu
CoddyTech

最大幅

CoddyのFlutterジャーニー「画面サイズに合わせたレイアウト」セクションの一部。レッスン 15/30。

長いテキストが入ったカードは、画面いっぱいの幅に広がります。スマートフォンでは問題ありませんが、タブレットでは同じカードが1000ピクセルもの長さの1行に伸びてしまい、読みにくくなります。

ConstrainedBoxは子ウィジェットのサイズに上限を設定します。maxWidth:は、幅が広がる最大値です。

ConstrainedBox(
  constraints: const BoxConstraints(maxWidth: 400),
  child: Container(...),
)

幅が400ピクセル未満の画面では、カードは画面に収まるように縮みます。幅が広い画面では400で止まり、テキストはさらに多くの行に折り返されます。

BoxConstraintsには、minWidth:、minHeight:、maxHeight:も指定できます。最小値は子ウィジェットが取りうる最小のサイズなので、子ウィジェットの成長を妨げることはありません。

challenge icon

チャレンジ

簡単

幅の広い画面でも引用カードを読みやすく保つため、幅が最大でも 320 ピクセルまで広がるようにしましょう。

自分で試してみよう

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Quote of the Day')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Center(
            child: Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.amber.shade100,
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Text(
                'The best way to learn to build apps is to build apps, one small screen at a time.',
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

画面サイズに合わせたレイアウトのすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ