Flutter如何使文本在Container容器中实现垂直水平完全居中?
问题核心原因
textAlign: TextAlign.center仅能控制文本自身的水平对齐规则,无法实现文本在父Container内的垂直方向居中效果,所以会出现你遇到的显示问题。
可用解决方案
方案1:为Container添加alignment配置(最简方案,推荐)
直接给每个承载文本的Container添加alignment: Alignment.center属性,即可让Container的所有子元素默认实现水平+垂直双居中:
// 修改后的单个Container示例 Container( margin: EdgeInsets.fromLTRB(75, 100, 75, 100), height: 100, width: 300, color: Colors.green, // 新增此行即可 alignment: Alignment.center, child: const Text('BLE & Data'), )
方案2:使用Center组件包裹Text
如果不需要修改Container的全局配置,也可以单独将Text嵌套在Center组件内,Center会自动将子元素在父容器内完全居中:
Container( margin: EdgeInsets.fromLTRB(75, 25, 75, 100), height: 100, width: 300, color: Colors.green, child: const Center( child: Text('Statistiken'), ), )
完整修改后参考代码
import 'package:flutter/material.dart'; class Homepage extends StatefulWidget { const Homepage({Key? key}) : super(key: key); @override _HomepageState createState() => _HomepageState(); } class _HomepageState extends State<Homepage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Homepage'), backgroundColor: Colors.green, ), body: SafeArea( child: Column( children: <Widget>[ Container( margin: EdgeInsets.fromLTRB(75, 100, 75, 100), height: 100, width: 300, color: Colors.green, alignment: Alignment.center, child: const Text('BLE & Data'), ), Container( margin: EdgeInsets.fromLTRB(75, 25, 75, 100), height: 100, width: 300, color: Colors.green, alignment: Alignment.center, child: const Text('Statistiken'), ), const SizedBox(height: 10), Container( margin: EdgeInsets.fromLTRB(75, 25, 75, 100), height: 100, width: 300, color: Colors.green, alignment: Alignment.center, child: const Text('Personal Data'), ), ], ), )); } }
内容的提问来源于stack exchange,提问作者Josef Göttlicher
相关产品推荐
相关产品推荐

