●Containerとは
透明の箱のウィジェット。色、サイズ、childの位置を指定することが可能。
コンテナの中にコンテナを入れることも可能。
●サンプル
黄色い100x100のサイズのコンテナの中に黒色の10x10のコンテナを入れる。
// FlutterのMaterialデザインライブラリをインポート
import 'package:flutter/material.dart';
// メイン関数: Flutterアプリケーションのエントリーポイント
void main() {
// 中心に配置された黒色の小さいコンテナウィジェットを作成
final con = Center(
child: Container(
color: Colors.black, // コンテナの背景色を黒に設定
width: 10, // コンテナの幅を10に設定
height: 10, // コンテナの高さを10に設定
));
// 黒色のコンテナを子に持つ、大きいamber色のコンテナウィジェットを作成
final con2 = Container(
color: Colors.amber, // コンテナの背景色をamberに設定
width: 100, // コンテナの幅を100に設定
height: 100, // コンテナの高さを100に設定
child: con, // 上で定義した小さい黒色のコンテナを子ウィジェットとして設定
);
// アプリケーションのルートウィジェットを定義
final a = MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min, // 列の主軸サイズを最小限に設定
children: [
const Text('test1'), // 最初のテキストウィジェット
con2, // 上で定義したamber色のコンテナウィジェット
const Text('test2'), // 二番目のテキストウィジェット
],
),
),
),
);
// runApp関数により、作成したウィジェットツリーをアプリケーションとして実行
runApp(a);
}
●位置の指定
パラメーターalignmentでchildに指定するウィジェットの位置を指定可能。
サンプルとしてAlignment.bottomCenterを指定して下側の中央に黒色コンテナを表示する。
●サンプル
import 'package:flutter/material.dart';
void main() {
final con = Container(
color: Colors.black,
width: 10,
height: 10,
);
final con2 = Container(
color: Colors.amber,
width: 100,
height: 100,
alignment: Alignment.bottomCenter,//下側の中央に表示
child: con,
);
final a = MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('test1'),
con2,
const Text('test2'),
],
),
),
),
);
runApp(a);
}