Flutter Container
The Container
widget is a convenience widget that combines common painting, positioning, and sizing widgets.
Syntax
Container({
Key? key,
AlignmentGeometry? alignment,
EdgeInsetsGeometry? padding,
Color? color,
Decoration? decoration,
Decoration? foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
EdgeInsetsGeometry? margin,
Matrix4? transform,
Widget? child,
})
Example
Container(
alignment: Alignment.bottomCenter,
padding: EdgeInsets.all(20),
color: Colors.blue,
child: Text(
'Hello World',
style: TextStyle(color: Colors.white),
),
)
Output
Explanation
The Container
widget can be used to style and position a single child widget inside it. In the above example, we have:
alignment
: Position the child widget on the bottom center of the container.padding
: Add 20px padding to all sides of the child widget.color
: Set the background color of the container to blue.child
: Add a single text widget as a child with white color text.
Use
- To add padding to a child widget.
- To set a background color or image for a child widget.
- To center a widget inside a parent widget.
- To add a border or shadow effect to a child widget.
Important Points
- If
height
orwidth
is set along withconstraints
, the former overrides the latter. - If
color
anddecoration
both are used, decoration takes precedence over color since decoration can add gradients, images, etc. - If the
child
parameter is null, it behaves like an emptyContainer
.
Summary
The Container
widget can be used to encapsulate a single child widget and apply painting, positioning, and sizing properties to it. It is a versatile widget that can be used to add padding, color, margin, etc., to a child. It is a useful widget in the Flutter framework and can greatly simplify layout and styling code.