How do I center text vertically and horizontally in Flutter?

北城余情 提交于 2020-05-24 16:42:05

问题


I'd like to know how to center the contents a Text widget vertically and horizontally in Flutter. I only know how to center the widget itself using Center(child: Text("test")) but not the content itself, it's by default left aligned. In Android, I believe the property of a TextView that achieves this is called gravity.

Example of what I want:


回答1:


Text alignment center property setting only horizontal alignment.

I used below code to set text vertically and horizontally center.

Code:

      child: Center(
        child: Text(
          "Hello World",
          textAlign: TextAlign.center,
        ),
      ),



回答2:


You can use TextAlign property of Text constructor.

Text("text", textAlign: TextAlign.center,)



回答3:


I think a more flexible option would be to wrap the Text() with Align() like so:

Align(
  alignment: Alignment.center, // Align however you like (i.e .centerRight, centerLeft)
  child: Text("My Text"),
),

Using Center() seems to ignore TextAlign entirely on the Text widget. It will not align TextAlign.left or TextAlign.right if you try, it will remain in the center.




回答4:


Text element inside Center of SizedBox work much better way, below Sample code

Widget build(BuildContext context) {
    return RawMaterialButton(
      fillColor: Colors.green,
      splashColor: Colors.greenAccent,
      shape: new CircleBorder(),
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(
              width: 100.0,
              height: 100.0,
              child: Center(
                child: Text(
                widget.buttonText,
                maxLines: 1,
                style: TextStyle(color: Colors.white)
              ),
              )
          )]
        ),
    ),
  onPressed: widget.onPressed
);
}

Enjoy coding 👨‍💻




回答5:


                       child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Text here',
                            textAlign: TextAlign.center,                          
                          ),
                        ),

This produced the best result for me.




回答6:


Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );


来源:https://stackoverflow.com/questions/50554110/how-do-i-center-text-vertically-and-horizontally-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!