Flutter-最簡單的 Container 使用範例

本文 source code

下面會介紹到Container常用的幾個屬性

child:放入子元件
color:背景顏色
alignment:對齊方式
width:容器寬度
height:容器高度
margin: 外部間距
padding: 內部間距


建立一個灰色底的Container

Container(color: Colors.grey,);

在原本Container中加入另外一個子Container

Container(
      color: Colors.grey,
      child: Container(
        color: Colors.blue,
      ),
    );

在灰色底圖上加入padding 分別設定內部上下左右需要的距離

Container(
      padding: EdgeInsets.only(left: 10, top: 20, right: 40, bottom: 80),
      color: Colors.grey,
      child: Container(
        color: Colors.blue,
      ),
    );

藍色底圖上再加入一個紅色底圖並同時設定margin控制與父Container所須距離

Container(
      padding: EdgeInsets.only(left: 10, top: 20, right: 40, bottom: 80),
      color: Colors.grey,
      child: Container(
        color: Colors.blue,
        child: Container(
          margin: EdgeInsets.all(50),
          color: Colors.red,
        ),
      ),
    );

在紅色Container底下給予一個黃色Container並設定大小

Container(
      padding: EdgeInsets.only(left: 10, top: 20, right: 40, bottom: 80),
      color: Colors.grey,
      child: Container(
        color: Colors.blue,
        child: Container(
          margin: EdgeInsets.all(50),
          color: Colors.red,
          child: Container(
            width: 130,
            height: 15,
            color: Colors.yellow,
          ),
        ),
      ),
    );
注意:這邊長寬資訊並未出現效果

因為Container預設是將child填滿,所以子畫面建立的width: 100, height: 100並未有效果

此時將紅色Container加入約束條件,

Container(
      padding: EdgeInsets.only(left: 10, top: 20, right: 40, bottom: 80),
      color: Colors.grey,
      child: Container(
        color: Colors.blue,
        child: Container(
          margin: EdgeInsets.all(50),
          color: Colors.red,
          alignment: Alignment.center,
          child: Container(
            width: 130,
            height: 15,
            color: Colors.yellow,
          ),
        ),
      ),
    );

修改約束條件進行測試

其他常用的alignment屬性,可自行測試效果

Alignment.topLeft
Alignment.topCenter
Alignment.topRight
Alignment.centerLeft
Alignment.center
Alignment.centerRight
Alignment.bottomLeft
Alignment.bottomCenter
Alignment.bottomRight

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *