flutter - 如何在下面的橙色矩形中居中标签?
问题描述
如何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());
解决方案
似乎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))),
);
推荐阅读
- macos - k8s/kind:无法通过 gRPC 连接到入口控制器
- python - 用于根据条件从列表中制作 2D 列表的 Pandas 代码
- python - 使用 pypika 生成带有“OUTPUT”子句的 SQL Server 查询
- r - 按相邻值分组记录
- go - 在 Go 中调用带有 (nil) 参数的结构是什么意思?
- sqlite - 可以使用正则表达式来计算 sqlite 中的平均值吗?
- javascript - 如何使用 ejs 循环来自后端的变量
- c++ - 如何声明 100 个相同类型的不同命名变量?
- python - 从字典创建列表
- laravel - Livewire:如何在传递参数时进行自定义分页