
Flutter
【Flutter】Widget内のコンテンツを画面からはみ出さずに表示する方法
作成日:2022年04月01日
更新日:2022年04月01日
例えば、Flutter で 4 つのコンテンツがあるとします。
dart
class _MyHomePageState extends State<MyHomePage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(color: Colors.red),
Container(color: Colors.blue),
Container(color: Colors.yellow),
Container(color: Colors.grey)
],
),
),
);
}
}
こちらを画面で確認すると、
何も表示されません。
これは、コンテンツのサイズを指定していないからです。
では、コンテンツにサイズを指定します。
dart
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(color: Colors.red, width: 300, height: 300),
Container(color: Colors.blue, width: 300, height: 300),
Container(color: Colors.yellow, width: 300, height: 300),
Container(color: Colors.grey, width: 300, height: 300)
],
),
),
ブラウザで確認すると、
コンテンツがはみ出してしまいました。
それぞれのコンテンツがはみ出ないよう、画面一杯に表示したい場合は、Expandedを使用します。
では、それぞれのContainerにExpandedを追加します。
dart
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(color: Colors.red, width: 300, height: 300)),
Expanded(
child: Container(color: Colors.blue, width: 300, height: 300)),
Expanded(
child:
Container(color: Colors.yellow, width: 300, height: 300)),
Expanded(
child: Container(color: Colors.grey, width: 300, height: 300))
],
),
ブラウザで確認すると、
コンテンツの高さ指定が無効になり、画面内で均等に表示されました。
height を削除しても、
dart
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(child: Container(color: Colors.red, width: 300)),
Expanded(child: Container(color: Colors.blue, width: 300)),
Expanded(child: Container(color: Colors.yellow, width: 300)),
Expanded(child: Container(color: Colors.grey, width: 300))
],
),
同じ結果が表示されます。
例えば、1 番目のコンテンツの Expanded を削除し、高さを指定すると、
dart
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(color: Colors.red, width: 300, height: 300),
Expanded(child: Container(color: Colors.blue, width: 300)),
Expanded(child: Container(color: Colors.yellow, width: 300)),
Expanded(child: Container(color: Colors.grey, width: 300))
],
),
1 番目のコンテンツがそのまま表示され、画面内の高さで、その他のコンテンツが均等に表示されました。
お知らせ

私事ですが、Udemyで初心者を対象にしたReactの動画コースを作成しました。
Reactについて興味がありましたら、ぜひ下のリンクからアクセスしてください。
詳しくはこちら(Udemyの外部サイトへ遷移します)