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 的基础,掌握它就掌握了布局的一半!

相关推荐
—Qeyser2 小时前
Flutter 生命周期完全指南:从出生到死亡的全过程
前端·javascript·flutter
HH思️️无邪2 小时前
Flutter 项目 -从 0 到 1 实现 iOS WatchApp
flutter·ios
—Qeyser2 小时前
Flutter StatelessWidget 完全指南:构建高效的静态界面
前端·flutter
小雨下雨的雨2 小时前
Flutter鸿蒙共赢——像素的解构:沃罗诺伊点描与权重平衡的艺术
flutter·ui·华为·harmonyos·鸿蒙系统
行者963 小时前
Flutter & OpenHarmony跨平台开发实现文件管理器
flutter·harmonyos·鸿蒙
摘星编程3 小时前
Flutter for OpenHarmony 实战:SliverList 滑动列表详解
android·javascript·flutter
Swift社区3 小时前
Flutter 的异步问题,为什么和前端 Promise 问题高度相似?
前端·flutter
摘星编程3 小时前
Flutter for OpenHarmony 实战:AlertDialog 警告对话框详解
flutter
leoyao1028063 小时前
基于 Dio 封装的 HTTP 请求工具类,支持配置化的请求头注入和统一的错误处理。
flutter