首页 > 解决方案 > 如何在下面的橙色矩形中居中标签?

问题描述

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

在此处输入图像描述

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());

标签: flutterdart

解决方案


似乎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))),
);

推荐阅读