The Center widget and Attributes.

The Center widget and Attributes.

ยท

2 min read

The Center widget is a simple layout widget in Flutter that centers its child within itself. It takes a single child and positions it at the center of the available space along both the horizontal and vertical axes.

Here's a basic example of using the Center widget:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Center Widget Example'),
        ),
        body: Center(
          child: Container(
            width: 100.0,
            height: 100.0,
            color: Colors.blue,
            child: Center(
              child: Text(
                'Centered Text',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Common Attributes:

The Center widget itself does not have many attributes, as its main purpose is to center its child. However, it can be combined with other widgets and layout controls to achieve more complex layouts.

Here are a few attributes that can be applied to the child widget within Center:

  1. width and height: Set the width and height of the child widget.

  2. color: Set the background color of the child widget.

  3. alignment: In case you need to align the child widget differently within the Center, you can use the alignment property.

Center(
  child: Container(
    width: 100.0,
    height: 100.0,
    color: Colors.blue,
    alignment: Alignment.bottomRight,
    child: Text(
      'Centered Text',
      style: TextStyle(color: Colors.white),
    ),
  ),
),

In this example, the Text widget is aligned to the bottom right within the Center widget.

Remember, the Center widget primarily centers its child, and you can further update the appearance and alignment of the child using the child widget's attributes.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย