0
0
FlutterHow-ToBeginner · 3 min read

How to Center Widget in Flutter: Simple Guide

To center a widget in Flutter, wrap it inside a Center widget. The Center widget aligns its child both vertically and horizontally in the available space.
📐

Syntax

The Center widget takes a single child widget and centers it within its parent. It expands to fill the available space and places the child in the middle.

  • child: The widget to be centered.
dart
Center(
  child: YourWidget(),
)
Output
A widget centered both vertically and horizontally inside its parent container.
💻

Example

This example shows a Text widget centered on the screen using the Center widget.

dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('Hello, centered!'),
        ),
      ),
    );
  }
}
Output
The app screen shows the text 'Hello, centered!' exactly in the center both vertically and horizontally.
⚠️

Common Pitfalls

Sometimes developers forget to use a widget that expands to fill the space, so Center has no room to center the child. For example, placing Center inside a widget that sizes itself tightly may not center as expected.

Also, using Align with incorrect alignment values can cause confusion.

dart
/* Wrong: Center inside a Column without expanded space */
Column(
  children: [
    Center(
      child: Text('Not centered vertically'),
    ),
  ],
)

/* Right: Wrap Center with Expanded to fill space */
Column(
  children: [
    Expanded(
      child: Center(
        child: Text('Centered vertically and horizontally'),
      ),
    ),
  ],
)
Output
Wrong example: Text is not vertically centered. Right example: Text is centered vertically and horizontally inside the column.
📊

Quick Reference

  • Center widget: Wrap any widget to center it.
  • Expanded + Center: Use inside flexible layouts like Column or Row.
  • Align widget: Use for custom alignment, but Center is simpler for centering.

Key Takeaways

Use the Center widget to easily center any child widget both vertically and horizontally.
Center expands to fill available space, so ensure its parent allows it to grow.
In flexible layouts like Column, wrap Center with Expanded to achieve vertical centering.
Avoid using Align with complex alignment if simple centering is needed.
Center is the simplest and most common way to center widgets in Flutter.