Container Widget
The Container widget is a convenience widget that combines common painting, positioning, and sizing widgets. It can be used to add padding, margins, borders, background color, or decorations to its child.
Properties
width
: number | string - Width of the containerheight
: number | string - Height of the containercolor
: string - Background color (default: “transparent”)padding
: EdgeInsets - Inner spacing (default: EdgeInsets.all(0))EdgeInsets.all(10) EdgeInsets.symmetric({ horizontal: 16, vertical: 8 }) EdgeInsets.only({ left: 8, top: 16, right: 8, bottom: 16 })
margin
: EdgeInsets - Outer spacing (default: EdgeInsets.all(0))alignment
: Alignment - How to align the child widgetAlignment.center Alignment.topLeft Alignment.bottomRight
decoration
: BoxDecoration - Advanced stylingnew BoxDecoration({ color: "white", borderRadius: BorderRadius.all(Radius.circular(8)) })
child
: Widget - The widget to containclipped
: boolean - Whether to clip child to the container’s boundstransform
: Matrix4 - Transform to apply to the container
Common Use Cases
-
Basic Container:
Container({ width: 100, height: 100, color: "lightblue" })
-
Container with Text:
Container({ color: "lightblue", child: Text("Hello", { style: new TextStyle({ fontSize: 30 }) }) })
-
Padded Container:
Container({ color: "lightblue", padding: EdgeInsets.all(10), child: Container({ color: "green", child: Text("Padded content") }) })
Best Practices
-
Layout Guidelines:
- Use width/height only when needed
- Prefer EdgeInsets for spacing
- Use alignment for positioning child
- Consider clipped for overflow control
-
Styling Guidelines:
- Use color for simple backgrounds
- Use BoxDecoration for complex styling
- Keep decorations consistent
- Consider reusable styles
-
Performance Tips:
- Cache EdgeInsets objects
- Use const constructors
- Avoid unnecessary nesting
- Consider layout constraints
Common Patterns
-
Rounded Container:
Container({ width: 300, height: 300, clipped: true, decoration: new BoxDecoration({ borderRadius: BorderRadius.all(Radius.circular(20)), color: "lightblue" }) })
-
Centered Content:
Container({ color: "lightblue", padding: EdgeInsets.all(10), alignment: Alignment.center, child: Text("Centered") })
-
Transformed Container:
Container({ width: 300, height: 300, color: "lightblue", transform: Matrix4.translationValues(10, 10, 0) })
Tips and Tricks
-
Spacing Tips:
- Use EdgeInsets.symmetric for equal spacing
- Consider margin for outer spacing
- Use padding for inner spacing
-
Decoration Tips:
- Use clipped with borderRadius
- Keep decorations simple
- Consider reusable styles
-
Layout Tips:
- Use alignment for positioning
- Consider transform for effects
- Keep nesting minimal