Center widget in Flutter (original) (raw)

Last Updated : 16 Nov, 2020

Center widget comes built-in with flutter, it aligns its child widget to the _cente_r of the available space on the screen. The size of this widget will be as big as possible if the widthFactor and heightFactor properties are set to null and the dimensions are constrained. And in case the dimensions are not constrained and the widthFactor and HeightFactor are set to null then the Center widget takes the size of its child widget. Let's understand this with the help of examples.

Constructor:

Syntax: Center({Key key, double widthFactor, double heightFactor, Widget child})

Properties of Center Widget:

Example:

The main.dart file.

Dart `

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget { // This widget is //the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); } }

class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); }

class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Center( // heightFactor: 3, // widthFactor: 0.8, child: Container( color: Colors.green, child: Text( 'Center Widget', textScaleFactor: 3, style: TextStyle(color: Colors.white), ), ), ), ); } }

`

Output:

When the above code is executed, the output is shown below:

center align widget

If the properties are defined as below:

heightFactor: 3,

The following design changes can be observed:

center top align widget

If the properties are defined as below:

widthFactor: 1,

The following design changes can be observed:

If the properties are defined as below:

heightFactor: 3, widthFactor: 0.8,

The following design changes can be observed:

Explanation: