flutter - 如何在下面的橙色矩形中居中放置标签?

标签 flutter dart

如何将标签2居中在橙色矩形中?我不想使用堆栈小部件。
enter image description here

import 'package:flutter/material.dart';

class Box extends StatelessWidget {
  const Box(this.text, this.color, {this.height = 100, this.alignment});
  final String text;
  final Color color;
  final double height;
  final Alignment alignment;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      height: height,
      alignment: alignment,
      child: text == null
          ? null
          : Center(
              child: Text(text,
                  style: TextStyle(fontSize: 50, color: Colors.white)),
            ),
    );
  }
}

class Puzzle extends StatelessWidget {
  Widget _buildR_1() => Row(children: [
        Expanded(flex: 2, child: const Box('1', Colors.red)),
        Expanded(flex: 1, child: Box(null, Colors.orange))
      ]);

  Widget _buildC() => Column(children: [
        Row(children: [
          Expanded(child: const Box('5', Colors.purple)),
          Expanded(
              child:
                  const Box('2', Colors.orange, alignment: Alignment(0, -2.5)))
        ]),
        const Box('3', Colors.blue)
      ]);

  Widget _buildR_2() => Row(children: [
        Expanded(flex: 1, child: const Box('4', Colors.green, height: 200)),
        Expanded(flex: 2, child: _buildC())
      ]);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(child: Column(children: [_buildR_1(), _buildR_2()])),
      ),
    );
  }
}

void main() => runApp(Puzzle());

最佳答案

似乎将Center用作子项会否定设置alignment的效果。沿以下几行更改build小部件的Box方法:

Widget build(BuildContext context) {
final _wrapper = (Widget child) => alignment == null 
  ? Center(child: child) 
  : Container(child: child);
                   
return Container(
  color: color,
  height: height,
  alignment: alignment,
  child: text == null
      ? null
      : _wrapper(Text(text,
              style: TextStyle(fontSize: 50, color: Colors.white))),
);

关于flutter - 如何在下面的橙色矩形中居中放置标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64497994/

相关文章:

flutter - flutter 如何获取星期几作为字符串

firebase - google_sign_in 包中的 getServerAuthToken 返回 null

android - 如何从列表中更新文本

json - 如何使用动态数组键解析 json?

dart - 从 ListTile 中删除前导和标题之间的填充

flutter - 底部不显示在底部

android - 点击时显示 Flutter 文本选择工具栏溢出

flutter - 如何在 Flutter 创建的应用程序中隐藏 AppBar

flutter - 如何用肘节改变 bool true false ?

list - Dart:如何创建一个空列表作为默认参数