In flutter we cannot directly put text widget at the center of a View layout. We have to use Center widget with Center text align property of Text and combination of both of them makes our Text at middle of View. In this tutorial for full explanation i am first creating a Container View with fixed height and set border around view. Then i am putting Center widget in Container and putting Text widget inside it. So in this tutorial we would Set Text Widget Vertically Horizontally Center in Flutter iOS Android App Example.
Contents in this project Set Text Widget Vertically Horizontally Center in Flutter iOS Android Example:
1. Import material.dart package in your app’s main.dart file.
1 |
import 'package:flutter/material.dart'; |
2. Create void main runApp() method and call our MyApp class here.
1 |
void main() => runApp(MyApp()); |
3. Create our main class named as MyApp extends with State less widget.
1 2 3 4 |
class MyApp extends StatelessWidget { } |
4. Create a SafeArea widget in Scaffold widget in Widget build area.
1 2 3 4 5 6 7 8 9 10 11 12 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( ) ) ); } } |
5. Now we would create a Container view widget with fixed height and border, So you all know that how much area our Container is occupying on device screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child : Container( decoration: BoxDecoration( border: Border.all( color: Color(0xff000000), width: 3, )), height: 200, child : ) ) ) ); } } |
6. Create a Center widget in Container widget and wrap Text widget in Center widget. We would also set text align as TextAlign.center.
1 2 3 4 5 6 |
Center( child: Text('Set Text Align Vertically and Horizontally Center in Flutter.', style: TextStyle(fontSize: 22), textAlign: TextAlign.center) ) |
7. 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 20 21 22 23 24 25 26 27 28 29 30 31 |
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 : Container( decoration: BoxDecoration( border: Border.all( color: Color(0xff000000), width: 3, )), height: 200, child : Center( child: Text('Set Text Align Vertically and Horizontally Center in Flutter.', style: TextStyle(fontSize: 22), textAlign: TextAlign.center) ) ) ) ) ); } } |
Screenshot in Android device: