Flutter: Detailed Usage of Center Widget
Flutter Center Widget - Detailed Usage
The Center widget is a simple but powerful widget used to place its child in the exact center of the area it's in.
Live Demo: Center Widget Examples
Try the Center widget in different scenarios in the interactive example below:
Basic Usage
Center takes a single child and centers it both horizontally and vertically:
Center(
child: Text('I am centered'),
)Center Inside Container
Centering Text relative to Container:
Container(
width: 200,
height: 100,
color: Colors.blue.shade100,
child: Center(
child: Text('In the center of Container'),
),
)In this example, Text is placed in the exact center of the Container.
Using Center Inside Row
When you use Center inside a Row, the Center widget centers its child according to the space allocated to it:
Container(
width: 300,
height: 100,
color: Colors.grey.shade200,
child: Row(
children: [
Container(width: 50, color: Colors.red),
Center(
child: Text('Centered in Row'),
),
Container(width: 50, color: Colors.green),
],
),
)Important Note: When Center is used inside Row, Center only uses the space allocated to it. To center the entire Row, you should use Row's own mainAxisAlignment property.
Centering the Row Itself
To center the entire Row, use Center outside the Row:
Container(
width: 300,
height: 100,
color: Colors.grey.shade200,
child: Center(
child: Row(
mainAxisSize: MainAxisSize.min, // Important: Keep Row compact
children: [
Icon(Icons.star),
SizedBox(width: 8),
Text('Row centered'),
SizedBox(width: 8),
Icon(Icons.star),
],
),
),
)Center vs mainAxisAlignment
Using Center
Container(
height: 200,
child: Center(
child: Text('With Center'),
),
)Using mainAxisAlignment
Container(
height: 200,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('With Axis'),
],
),
)Difference: Center always centers both horizontally and vertically. mainAxisAlignment only aligns along the main axis.
When to Use Center, When to Use Axis Alignment?
Use Center:
- To center a single widget completely
- When both horizontal and vertical centering is needed
- When you want a simple and quick solution
Use mainAxisAlignment/crossAxisAlignment:
- When aligning multiple widgets
- When you'll only align on one axis
- When you need more control (spaceBetween, spaceAround, etc.)
Practical Examples
Example 1: Loading Indicator
Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
)Example 2: Empty State Screen
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.inbox, size: 64, color: Colors.grey),
SizedBox(height: 16),
Text('No content yet'),
],
),
)Summary
The Center widget:
- Centers its child both horizontally and vertically
- Takes a single child
- Is simple and easy to use
- Works differently inside Container, Row, Column
- Is simpler than mainAxisAlignment/crossAxisAlignment but less flexible
When used in the right scenario, Center is a quick and effective alignment solution.