Center widget in flutter is used to put any given child widget in Vertically and Horizontally center of remaining space. In many applications when developer wants to show something at Center of screen then the solution is Center widget. Today we would learn about a basic concept in flutter to show any widget in Center of screen. Flutter Align Container Widget Center of Screen Android iOS Example.
Contents in this project Flutter Align Container Widget Center of Screen Example:
1. Open your project’s main.dart file and import material.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Create void main runApp() method and here we would call our main MyApp class.
1 |
void main() => runApp(MyApp()); |
3. Creating our main class MyApp extends Statelesswidget.
1 2 3 4 5 |
class MyApp extends StatelessWidget { } |
4. Creating Widget Build area -> Material App -> Scaffold Widget -> Safe Area widget . Here the Safe Area widget is used to put margin between Top Navbar and screen.
1 2 3 4 5 6 7 8 9 10 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: ))); } } |
5. Now in the final step we would make the Center Widget then wrap the Container widget as its child. This will put the Container widget in Center of Screen.
1 2 3 4 5 6 7 8 |
Center( child: Container( padding: const EdgeInsets.all(0.0), color: Colors.blue, width: 120.0, height: 120.0, ) ) |
6. Complete source code for main.dart file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: Center( child: Container( padding: const EdgeInsets.all(0.0), color: Colors.blue, width: 120.0, height: 120.0, ))))); } } |
Screenshot: