You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:54:01