I’m trying to horizontally center a text. Please check the below code.
import 'package:flutter/material.dart'; class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Container( color: Colors.black, child: Row( children: <Widget>[ Column( children: <Widget>[_buildTitle()], ), ], )); } Widget _buildTitle() { return Center(child: Container( margin: EdgeInsets.only(top: 100), child: Column( children: <Widget>[ Text( "something.xyz", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25,), textAlign: TextAlign.center, ), ], ), ),); } }
This did not center horizontally, instead gave the following output. The margins etc is fine.
How can I fix this?
In flutter, we cannot directly put a text widget at the center of a View layout. We have to use the Center widget with the Center text-align property of Text. Moreover, a combination of both of them makes our Text in the middle of View.
try this
import 'package:flutter/material.dart'; void main() => runApp(MaterialApp(home: LoginPage())); class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( body: Container( color: Colors.black, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[_buildTitle()], ), ], )), ); } Widget _buildTitle() { return Center( child: Container( margin: EdgeInsets.only(top: 100), child: Column( children: <Widget>[ Text( "something.xyz", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 25, ), // textAlign: TextAlign.center, ), ], ), ), ); } }
You can also solve it with a Container
and TextAlign
:
Container( width: double.infinity, child: Text( 'something.xyz', textAlign: TextAlign.center, ), )
In this case, the container takes up the entire width with double.infinity
. The text adapts to the container and can be moved to the middle of the screen with TextAlign.center
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With