You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中创建具有固定宽高的颜色盒子?

How to Create a Fixed-Size Colored Box in Flutter

Hey there! Creating a fixed-width and fixed-height colored box in Flutter is actually a common, straightforward task—let me walk you through a couple of reliable, practical approaches with code examples you can use right away.

Container is the go-to widget for this job because it lets you set dimensions, background color, and extra styling all in one place. Here’s a basic, fully functional example:

Container(
  // Define fixed width and height
  width: 200,
  height: 150,
  // Set background color
  color: Colors.blueAccent,
  // Optional: Add spacing and advanced styling
  margin: const EdgeInsets.all(16), // Space around the box
  padding: const EdgeInsets.symmetric(vertical: 8), // Space inside the box
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(8), // Rounded corners
    border: Border.all(color: Colors.black, width: 2), // Add a border
  ),
  // Optional: Add child content inside the box
  child: const Center(
    child: Text(
      "Fixed Size Box",
      style: TextStyle(color: Colors.white, fontSize: 18),
    ),
  ),
)

Note: If you use the decoration property for advanced styling (like borders or gradients), don’t set the top-level color property—define the background color inside BoxDecoration.color instead (Flutter won’t let you use both at once!).

2. Combine SizedBox and DecoratedBox

If you want to separate the size constraint from visual styling (great for reusing styles across different boxes), wrap a DecoratedBox inside a SizedBox:

SizedBox(
  width: 200,
  height: 150,
  child: DecoratedBox(
    decoration: const BoxDecoration(
      color: Colors.greenAccent,
      // Add extra effects like shadows
      boxShadow: [
        BoxShadow(
          color: Colors.grey,
          blurRadius: 4,
          offset: Offset(2, 2),
        ),
      ],
    ),
    child: const Center(
      child: Text("SizedBox + DecoratedBox", style: TextStyle(fontSize: 16)),
    ),
  ),
)

Here, SizedBox locks in the fixed dimensions, while DecoratedBox handles all the visual customization.

Quick Extra Tips

  • If you need a box that adapts to space but has max/min bounds, use ConstrainedBox instead of fixed width/height.
  • To maintain a consistent aspect ratio (e.g., 1:1 square) while fitting available space, wrap your Container in an AspectRatio widget.

内容的提问来源于stack exchange,提问作者Tree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:45:48