flutter
/

Flutter Container Widget – Complete Guide with Examples

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Flutter Container Widget – Complete Guide with Examples

What is Container in Flutter?

Container is a versatile widget that combines common painting, positioning, and sizing widgets. It's one of the most frequently used widgets in Flutter because it provides a simple way to add padding, margins, borders, background color, or decoration to a child widget. Container can be thought of as a box that can hold a single child and style it according to your needs.

Basic Usage

DARTRead-only
1
Container(
  child: Text('Hello, Flutter!'),
  padding: EdgeInsets.all(16.0),
  color: Colors.blue,
)

In its simplest form, you provide a child and some styling. The above creates a blue box with 16 pixels of padding around the text.

Common Properties

    • child: The widget inside the container (can be null).
    • padding: Empty space inside the container around the child.
    • margin: Empty space outside the container.
    • color: Background color (cannot be used together with decoration).
    • decoration: A BoxDecoration for more complex styling (border, gradient, shadow).
    • width / height: Fixed dimensions (in logical pixels).
    • alignment: Aligns the child within the container (e.g., Alignment.center).
    • constraints: Additional sizing constraints (e.g., BoxConstraints(maxWidth: 200)).
    • transform: Applies a transformation (e.g., Matrix4.rotationZ(0.2)).

Padding and Margin

padding adds space inside the container, between the container's edges and its child. margin adds space outside the container, separating it from neighboring widgets. Both are EdgeInsetsGeometry objects.

DARTRead-only
1
Container(
  margin: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
  padding: EdgeInsets.all(16),
  color: Colors.green,
  child: Text('Padded and Margined'),
)

Decoration: BoxDecoration

For rich styling, use decoration with BoxDecoration. It supports:

  • color (background, but can't be used if color property is set)
  • borderRadius (rounded corners)
  • boxShadow (drop shadows)
  • gradient (linear, radial, sweep)
  • border (border around the container)
  • image (background image)
DARTRead-only
1
Container(
  width: 200,
  height: 200,
  decoration: BoxDecoration(
    gradient: LinearGradient(
      colors: [Colors.red, Colors.blue],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    ),
    borderRadius: BorderRadius.circular(16),
    boxShadow: [
      BoxShadow(
        color: Colors.grey.withOpacity(0.5),
        spreadRadius: 5,
        blurRadius: 7,
        offset: Offset(0, 3),
      ),
    ],
  ),
  child: Center(
    child: Text(
      'Gradient Container',
      style: TextStyle(color: Colors.white, fontSize: 18),
    ),
  ),
)

Note: You cannot set both color and decoration. If you need a background color with decoration, include the color inside the BoxDecoration.

Sizing and Constraints

Container tries to size itself to its child, but you can override this by providing width, height, or constraints. If no child is given and no explicit size, the container expands to fill the available space (like a SizedBox.expand). The actual size is also affected by the parent's constraints.

DARTRead-only
1
// Fixed size
Container(
  width: 100,
  height: 100,
  color: Colors.orange,
)

// Expand to fill parent (since no child)
Container(
  color: Colors.purple,
)

// Constrained size
Container(
  constraints: BoxConstraints(maxWidth: 200, minHeight: 50),
  child: Text('This container cannot be wider than 200 pixels'),
)

Container vs Other Widgets

    • SizedBox: Use when you only need a fixed size or a simple space.
    • ColoredBox: If you only need a background color, ColoredBox is more efficient.
    • DecoratedBox: For decoration without padding or margin.
    • Padding / Align: Specialized widgets for single purposes.
    • Container is convenient but can be overkill for simple use cases. Use the most specific widget for clarity and performance.

Common Mistakes

    • Using both color and decoration (throws an assertion).
    • Forgetting that padding and margin are separate; mixing them up leads to unexpected spacing.
    • Assuming a Container without a child will always fill the available space (it will, but only if constraints allow).
    • Using Container when a simpler widget like SizedBox or ColoredBox would suffice – this can hurt performance in large lists.

Best Practices

    • Always use const constructors when possible for compile‑time constants (e.g., const Container()).
    • For reusable styles, consider extracting the decoration into a variable or using a Theme.
    • Use SizedBox.shrink() or Container.shrink() to create empty widgets when needed.
    • Prefer EdgeInsets.only, EdgeInsets.symmetric, or EdgeInsets.fromLTRB for specific paddings.

Complete Example

DARTRead-only
1
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Container Demo')),
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              gradient: const LinearGradient(
                colors: [Colors.pink, Colors.purple],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              boxShadow: const [
                BoxShadow(
                  color: Colors.black26,
                  blurRadius: 10,
                  offset: Offset(0, 5),
                ),
              ],
            ),
            padding: const EdgeInsets.all(20),
            child: const Text(
              'Hello!',
              style: TextStyle(color: Colors.white, fontSize: 24),
            ),
          ),
        ),
      ),
    );
  }
}

Key Takeaways

    • Container is a multi‑purpose widget for styling and positioning a child.
    • Use padding for internal spacing, margin for external spacing.
    • For complex styling (borders, gradients, shadows), use decoration with BoxDecoration.
    • You cannot set both color and decoration; use decoration with a color inside.
    • Container sizes itself to its child, but can be constrained by width, height, or constraints.
    • Always consider using a more specific widget for performance when possible.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Container Example')),
        body: Center(
          child: Container(
            width: 150,
            height: 150,
            decoration: BoxDecoration(
              color: Colors.teal,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Center(
              child: Text(
                'Hello',
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
          ),
        ),
      ),
    ),
  );
}

Test Your Knowledge

Q1
of 4

What is the purpose of Container in Flutter?

A
To only hold text
B
To combine painting, positioning, and sizing of a child
C
To replace all layout widgets
D
To manage app state
Q2
of 4

Which property adds space outside the Container?

A
padding
B
margin
C
alignment
D
decoration
Q3
of 4

What happens if you set both `color` and `decoration` on a Container?

A
The decoration is ignored
B
The color is applied and decoration is applied on top
C
The app crashes with an assertion error
D
The container renders with only the color
Q4
of 4

Which widget is a more performant alternative if you only need a background color?

A
SizedBox
B
ColoredBox
C
DecoratedBox
D
Padding

Frequently Asked Questions

Can I use both `color` and `decoration` in a Container?

No, Container throws an assertion if you set both. Use color inside the BoxDecoration if you need a background color with additional styling.

What is the difference between `padding` and `margin`?

padding adds space inside the container, between its edges and the child. margin adds space outside the container, between the container and its parent or siblings.

How does Container determine its size?

If a width and/or height are provided, the container respects those. Otherwise, it tries to size itself to its child. If there is no child and no size, the container expands to fill the available space given by its parent constraints.

Is Container expensive to use?

Container is slightly heavier than more specialized widgets like SizedBox or ColoredBox because it combines multiple functions. For performance‑critical code (e.g., long lists), use the simpler widgets when possible.

Can Container have multiple children?

No, Container can only have one child. If you need multiple children, wrap them in a Column, Row, Stack, or ListView inside the container.

Previous

flutter statelesswidget

Next

flutter row column

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.