09. Flutter的常用佈局Widget:Container

A convenience widget that combines common painting(繪製), positioning(定位), and sizing(大小) widgets.

它是DecoratedBox、ConstrainedBox、Transform、Padding、Align等Widget組合的多功能容器,我們只需通過它便可實现同時需要裝飾、變換、限制的場合。

  • 容器的基本佈局
    layout

Container常用參數

參數 說明
alignment 對齊,可使用Alignment.center等值
padding 容器內的填充值
margin 容器外的邊界值
width、height 寬度與高度
color 容器背景色,不能和decoration並存
decoration 繪製child之背景部份的裝飾
foregroundDecoration 繪製child之前景的裝飾
constraints 容器大小的限制條件
transform 設容器的變換矩陣,型別是Matrix4
child 容器的內容

decoration參數經常使用BoxDecoration class。

BoxDecoration

BoxDecoration提供了多種繪製盒子的方法。

BoxDecoration常用參數

參數 說明
color 背景色
backgroundBlendMode 背景混合模式
border 邊框;Border.all(Colors.red)
borderRadious 圓角角度
boxShadow 陰影; List [BoxShadow]
shape Box的形狀(圓或方)
gradient 漸層效果;LinearGradient(), RadialGradient
image 背景圖;DecorationImage

逐次添加Container的多個參數

  1. 先加color使容器易於觀察
  2. 加上容器的寬和高
  3. 讓子物件對齊(alignment)
  4. 加上邊界(margin)移動容器之位置
  5. 加上填充(padding)讓子物件移動位置
  6. 用transform旋轉容器
  7. 用Center置中容器
  8. 最後用decoration來裝飾:
    1. decoration與color不能同時存在,因此先刪去color
    2. 加上邊框(Border.all)
    3. 變更為圓角矩形(borderRadius)
    4. 加上color為背景色
    5. 變更為漸層背景色
    6. 加上陰影
    7. 加上容器的背景圖片

Flutter載入本機圖檔的寫法

  1. 本地圖檔使用AssetImage
image: DecorationImage(
  image: AssetImage("assets/images/flutter-demo7.png"),
  fit: BoxFit.contain,
),
  1. 遠端圖檔使用
image: DecorationImage(
  image: NetworkImage("https://flutter.dev/images/flutter-mono-81x100.png"),
  fit: BoxFit.none,
),
  1. 外部資源設定
    外部資源必須在 pubspec.yaml 設定檔裡設置。

    1. 將圖檔複製到專案根目錄下的 assests/images (目錄自訂)
    2. 搜尋pubspec.yaml assets設定,修改如下:
  assets:
    - assets/images/
  1. IDEA的pubspec.yaml分頁偵測到變更後,點選upgrade

demo9_container_test.dart

解說影片


##

您可能也會有興趣的類似文章

簡睿

服務於軟體業的資訊老兵。興趣廣泛,學習力佳,樂於分享所知所學。

您可能也會喜歡…

發佈留言

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