Flutter Container 容器组件完全指南

Flutter Container 容器组件完全指南

什么是 Container?

Container 是 Flutter 中最常用的组件之一,就像一个"万能盒子",可以用来:

  • 设置宽高
  • 添加内外边距
  • 设置背景颜色和装饰
  • 添加边框和圆角
  • 对齐子组件

简单理解: Container = HTML 中的 div

基础用法

最简单的 Container

dart 复制代码
Container(
  child: Text('Hello'),
)

设置宽高

dart 复制代码
Container(
  width: 200,
  height: 100,
  child: Text('固定大小'),
)

设置颜色

dart 复制代码
Container(
  width: 200,
  height: 100,
  color: Colors.blue,
  child: Text('蓝色背景'),
)

常用属性

1. 尺寸属性

dart 复制代码
Container(
  width: 200,        // 宽度
  height: 100,       // 高度
  child: Text('固定尺寸'),
)

// 占满父组件
Container(
  width: double.infinity,   // 宽度占满
  height: double.infinity,  // 高度占满
  child: Text('占满'),
)

2. 内边距 padding

dart 复制代码
// 所有方向相同
Container(
  padding: EdgeInsets.all(20),
  child: Text('四周 20 像素'),
)

// 水平和垂直
Container(
  padding: EdgeInsets.symmetric(
    horizontal: 20,  // 左右
    vertical: 10,    // 上下
  ),
  child: Text('不同边距'),
)

// 单独设置每个方向
Container(
  padding: EdgeInsets.only(
    left: 10,
    top: 20,
    right: 30,
    bottom: 40,
  ),
  child: Text('自定义边距'),
)

// 从左上开始顺时针
Container(
  padding: EdgeInsets.fromLTRB(10, 20, 30, 40),
  child: Text('LTRB 方式'),
)

3. 外边距 margin

dart 复制代码
Container(
  margin: EdgeInsets.all(20),
  color: Colors.blue,
  child: Text('外边距'),
)

4. 对齐 alignment

dart 复制代码
Container(
  width: 200,
  height: 200,
  color: Colors.blue,
  alignment: Alignment.center,        // 居中
  child: Text('居中'),
)

// 其他对齐方式
alignment: Alignment.topLeft,        // 左上
alignment: Alignment.topCenter,      // 上中
alignment: Alignment.topRight,       // 右上
alignment: Alignment.centerLeft,     // 左中
alignment: Alignment.center,         // 正中
alignment: Alignment.centerRight,    // 右中
alignment: Alignment.bottomLeft,     // 左下
alignment: Alignment.bottomCenter,   // 下中
alignment: Alignment.bottomRight,    // 右下

5. 装饰 decoration

注意:使用 decoration 时不能同时使用 color 属性!

dart 复制代码
Container(
  width: 200,
  height: 100,
  decoration: BoxDecoration(
    color: Colors.blue,              // 背景色
    borderRadius: BorderRadius.circular(10),  // 圆角
  ),
  child: Text('圆角容器'),
)

装饰详解 BoxDecoration

1. 圆角

dart 复制代码
// 所有角相同圆角
decoration: BoxDecoration(
  color: Colors.blue,
  borderRadius: BorderRadius.circular(20),
)

// 单独设置每个角
decoration: BoxDecoration(
  color: Colors.blue,
  borderRadius: BorderRadius.only(
    topLeft: Radius.circular(20),
    topRight: Radius.circular(20),
    bottomLeft: Radius.circular(0),
    bottomRight: Radius.circular(0),
  ),
)

// 圆形
decoration: BoxDecoration(
  color: Colors.blue,
  shape: BoxShape.circle,  // 必须是正方形才能显示为圆
)

2. 边框

dart 复制代码
decoration: BoxDecoration(
  color: Colors.white,
  border: Border.all(
    color: Colors.blue,
    width: 2,
  ),
  borderRadius: BorderRadius.circular(10),
)

// 单独设置每条边
decoration: BoxDecoration(
  border: Border(
    top: BorderSide(color: Colors.red, width: 2),
    bottom: BorderSide(color: Colors.blue, width: 2),
    left: BorderSide(color: Colors.green, width: 2),
    right: BorderSide(color: Colors.orange, width: 2),
  ),
)

3. 阴影

dart 复制代码
decoration: BoxDecoration(
  color: Colors.white,
  borderRadius: BorderRadius.circular(10),
  boxShadow: [
    BoxShadow(
      color: Colors.grey.withOpacity(0.5),
      spreadRadius: 5,
      blurRadius: 7,
      offset: Offset(0, 3),  // 阴影位置
    ),
  ],
)

4. 渐变

dart 复制代码
// 线性渐变
decoration: BoxDecoration(
  gradient: LinearGradient(
    colors: [Colors.blue, Colors.purple],
    begin: Alignment.topLeft,
    end: Alignment.bottomRight,
  ),
)

// 径向渐变
decoration: BoxDecoration(
  gradient: RadialGradient(
    colors: [Colors.yellow, Colors.orange, Colors.red],
  ),
)

// 扫描渐变
decoration: BoxDecoration(
  gradient: SweepGradient(
    colors: [Colors.red, Colors.yellow, Colors.green, Colors.blue, Colors.red],
  ),
)

5. 背景图片

dart 复制代码
decoration: BoxDecoration(
  image: DecorationImage(
    image: NetworkImage('https://example.com/image.jpg'),
    fit: BoxFit.cover,
  ),
)

实战案例

案例1:卡片样式

dart 复制代码
Container(
  width: 300,
  padding: EdgeInsets.all(20),
  margin: EdgeInsets.all(10),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(15),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.3),
        spreadRadius: 2,
        blurRadius: 5,
        offset: Offset(0, 3),
      ),
    ],
  ),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      Text(
        '标题',
        style: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 10),
      Text('这是卡片内容,可以放任何组件'),
    ],
  ),
)

案例2:渐变按钮

dart 复制代码
Container(
  width: 200,
  height: 50,
  decoration: BoxDecoration(
    gradient: LinearGradient(
      colors: [Colors.blue, Colors.purple],
    ),
    borderRadius: BorderRadius.circular(25),
    boxShadow: [
      BoxShadow(
        color: Colors.blue.withOpacity(0.5),
        blurRadius: 10,
        offset: Offset(0, 5),
      ),
    ],
  ),
  child: Material(
    color: Colors.transparent,
    child: InkWell(
      onTap: () {
        print('点击了渐变按钮');
      },
      borderRadius: BorderRadius.circular(25),
      child: Center(
        child: Text(
          '渐变按钮',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    ),
  ),
)

案例3:头像框

dart 复制代码
Container(
  width: 100,
  height: 100,
  decoration: BoxDecoration(
    shape: BoxShape.circle,
    border: Border.all(
      color: Colors.blue,
      width: 3,
    ),
    image: DecorationImage(
      image: NetworkImage('https://example.com/avatar.jpg'),
      fit: BoxFit.cover,
    ),
  ),
)

案例4:标签

dart 复制代码
Container(
  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(20),
  ),
  child: Text(
    '热门',
    style: TextStyle(
      color: Colors.white,
      fontSize: 12,
    ),
  ),
)

案例5:带边框的输入框样式

dart 复制代码
Container(
  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
  decoration: BoxDecoration(
    color: Colors.grey[100],
    borderRadius: BorderRadius.circular(10),
    border: Border.all(
      color: Colors.grey[300]!,
      width: 1,
    ),
  ),
  child: TextField(
    decoration: InputDecoration(
      border: InputBorder.none,
      hintText: '请输入内容',
    ),
  ),
)

案例6:通知徽章

dart 复制代码
Stack(
  children: [
    Icon(Icons.notifications, size: 40),
    Positioned(
      right: 0,
      top: 0,
      child: Container(
        padding: EdgeInsets.all(4),
        decoration: BoxDecoration(
          color: Colors.red,
          shape: BoxShape.circle,
        ),
        constraints: BoxConstraints(
          minWidth: 20,
          minHeight: 20,
        ),
        child: Center(
          child: Text(
            '9',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12,
            ),
          ),
        ),
      ),
    ),
  ],
)

案例7:价格标签

dart 复制代码
Container(
  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
  decoration: BoxDecoration(
    gradient: LinearGradient(
      colors: [Colors.orange, Colors.red],
    ),
    borderRadius: BorderRadius.only(
      topRight: Radius.circular(10),
      bottomLeft: Radius.circular(10),
    ),
  ),
  child: Text(
    '¥99',
    style: TextStyle(
      color: Colors.white,
      fontSize: 16,
      fontWeight: FontWeight.bold,
    ),
  ),
)

案例8:进度条样式

dart 复制代码
Container(
  width: 300,
  height: 20,
  decoration: BoxDecoration(
    color: Colors.grey[300],
    borderRadius: BorderRadius.circular(10),
  ),
  child: FractionallySizedBox(
    alignment: Alignment.centerLeft,
    widthFactor: 0.7,  // 70% 进度
    child: Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue, Colors.purple],
        ),
        borderRadius: BorderRadius.circular(10),
      ),
    ),
  ),
)

完整示例

dart 复制代码
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ContainerDemo(),
    );
  }
}

class ContainerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Container 示例')),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            // 基础容器
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20),
              color: Colors.blue,
              child: Text(
                '基础容器',
                style: TextStyle(color: Colors.white),
              ),
            ),
            SizedBox(height: 20),

            // 圆角容器
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.green,
                borderRadius: BorderRadius.circular(15),
              ),
              child: Text(
                '圆角容器',
                style: TextStyle(color: Colors.white),
              ),
            ),
            SizedBox(height: 20),

            // 带阴影的卡片
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(15),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.5),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '卡片标题',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 10),
                  Text('这是一个带阴影的卡片容器'),
                ],
              ),
            ),
            SizedBox(height: 20),

            // 渐变容器
            Container(
              width: double.infinity,
              height: 100,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.purple, Colors.blue],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Center(
                child: Text(
                  '渐变容器',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
              ),
            ),
            SizedBox(height: 20),

            // 带边框的容器
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                  color: Colors.blue,
                  width: 2,
                ),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Text('带边框的容器'),
            ),
            SizedBox(height: 20),

            // 圆形容器
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      '圆',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: Colors.orange,
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      '形',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: Colors.green,
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      '容器',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

常见问题

1. color 和 decoration 不能同时使用

dart 复制代码
// ❌ 错误
Container(
  color: Colors.blue,
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(10),
  ),
)

// ✅ 正确
Container(
  decoration: BoxDecoration(
    color: Colors.blue,
    borderRadius: BorderRadius.circular(10),
  ),
)

2. 如何让 Container 占满父组件?

dart 复制代码
Container(
  width: double.infinity,
  height: double.infinity,
  color: Colors.blue,
)

3. 如何设置最小/最大尺寸?

dart 复制代码
Container(
  constraints: BoxConstraints(
    minWidth: 100,
    maxWidth: 300,
    minHeight: 50,
    maxHeight: 200,
  ),
  child: Text('有尺寸限制'),
)

4. 圆形容器不显示为圆形?

必须保证宽高相等:

dart 复制代码
// ✅ 正确
Container(
  width: 100,
  height: 100,  // 宽高相等
  decoration: BoxDecoration(
    color: Colors.blue,
    shape: BoxShape.circle,
  ),
)

属性速查表

属性 类型 说明
width double 宽度
height double 高度
color Color 背景颜色
padding EdgeInsets 内边距
margin EdgeInsets 外边距
alignment Alignment 对齐方式
decoration BoxDecoration 装饰(圆角、边框、阴影等)
constraints BoxConstraints 尺寸约束
transform Matrix4 变换(旋转、缩放等)
child Widget 子组件

总结

Container 的核心用途:

  1. 设置尺寸和颜色
  2. 添加内外边距
  3. 设置圆角和边框
  4. 添加阴影效果
  5. 创建渐变背景
  6. 对齐子组件

记住:

  • Container 是最常用的布局组件
  • 使用 decoration 时不能用 color
  • 圆形容器需要宽高相等
  • 善用 BoxDecoration 可以创造丰富的视觉效果

Container 是 Flutter 的基础,掌握它就掌握了布局的一半!

相关推荐
大龄秃头程序员2 分钟前
Flutter 动画随笔:业务里真正高频的几类控件
flutter
天空之城--1 小时前
Android Flutter行业最新动态与实用参考(2026年8月第2周)
android·flutter
恋猫de小郭2 小时前
Flutter 3.47 发布,快来看看有什么更新吧
android·前端·flutter
大龄秃头程序员17 小时前
一次 Flutter 动画 Demo 的整理与复盘
flutter
AlexMaybeBot20 小时前
躺在沙发上开发 Openclaw 的移动端APP
前端·flutter
天空之城--21 小时前
Android Flutter行业动态与学习参考(2026年8月)
android·flutter
FungLeo21 小时前
Flutter Web token 存储陷阱:crypto.subtle 在非安全上下文失效排查实录
前端·安全·flutter
FungLeo1 天前
Flutter Web 中文字体困境与渲染器选择:CanvasKit vs HTML renderer 实战
前端·flutter·html
杉氧1 天前
原生交互:如何在 Flutter 中嵌入 Android/iOS 原生组件并解决手势冲突
android·flutter·dart
恋猫de小郭1 天前
Flutter iOS Deep Link 为什么会突然失效:一系列难以言喻的问题
android·前端·flutter