この記事では、FlutterのContainerウィジェットの使い方について書いていきます。
サンプル
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(
home: Scaffold(
appBar: AppBar(title: const Text('MainAxisAlignment sample')),
body: Center(
child: Column(
// 主軸(縦方向)の中央に配置
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 200,
height: 100,
// 外側の余白
margin: const EdgeInsets.all(16.0),
// 内側の余白
padding: const EdgeInsets.all(12.0),
// 子要素の配置(中央寄せ)
alignment: Alignment.center,
// デザインの装飾(※ color は decoration の中に書く必要があります)
decoration: BoxDecoration(
color: Colors.blue, // 背景色
borderRadius: BorderRadius.circular(12.0), // 角丸
border: Border.all(color: Colors.black, width: 2), // 枠線
boxShadow: const [
BoxShadow(
color: Colors.grey,
blurRadius: 5.0,
offset: Offset(2, 2), // 影
),
],
),
// 中身のウィジェット
child: const Text(
'Containerの例',
style: TextStyle(color: Colors.white),
),
),
Container(
width: 200,
height: 100,
// 外側の余白
margin: const EdgeInsets.all(16.0),
// 内側の余白
padding: const EdgeInsets.all(12.0),
// 子要素の配置(中央寄せ)
alignment: Alignment.center,
// デザインの装飾(※ color は decoration の中に書く必要があります)
decoration: BoxDecoration(
color: const Color.fromARGB(255, 3, 252, 102), // 背景色
borderRadius: BorderRadius.circular(12.0), // 角丸
border: Border.all(color: Colors.black, width: 2), // 枠線
boxShadow: const [
BoxShadow(
color: Colors.grey,
blurRadius: 5.0,
offset: Offset(2, 2), // 影
),
],
),
// 中身のウィジェット
child: const Text(
'Containerの例',
style: TextStyle(color: Colors.red),
),
)
],
),
),
),
);
}
}
Containerウィジェット(よく使用するプロパティ)
containerウィジェットはContainer内部で定めた見た目の装飾・余白・配置・サイズをひとまとめに変更したい場合に使用します。
よく使用されるプロパティをまとめました。
| プロパティ | 型 | 概要 |
|---|---|---|
| width / height | double | 横幅と高さを指定(未指定時は親や子に合わせる) |
| color | Color | 背景色を指定(decorationと同時使用不可) |
| padding | EdgeInsetsGeometry | 内側の余白(内側のコンテンツとの距離) |
| margin | EdgeInsetsGeometry | 外側の余白(他のウィジェットとの距離) |
| decoration | Decoration | 角丸、枠線、背景画像、影などの装飾(BoxDecorationを使用) |
| alignment | AlignmentGeometry | 子ウィジェットの配置位置(Alignment.center など) |
| constraints | BoxConstraints | 最小・最大の幅や高さを制限 |
| transform | Matrix4 | 回転や拡大・縮小などの変形を適用 |
| child | Widget | Containerの中に配置する単一のウィジェット |
