需求
这是 UI 设计图:
文本布局在水平方向上是居中的。
我首先想到的是用 Text.rich
+ TextSpan
来实现,为了方便说明问题,我用 AB CD EF 替代前中后三部分。
这是代码:
import 'package:flutter/material.dart';
class DraftPage extends StatefulWidget {
DraftPage({Key key}) : super(key: key);
@override
_DraftPageState createState() => _DraftPageState();
}
class _DraftPageState extends State<DraftPage> {
@override
Widget build(BuildContext context) {
final smallTextStyle = TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: Colors.red,
);
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Container(
alignment: Alignment.center,
width: 300,
height: 57,
decoration: BoxDecoration(
color: Colors.yellow,
),
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: 'AB',
style: smallTextStyle,
),
TextSpan(
text: 'CD',
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.w500,
color: Colors.blue,
),
),
TextSpan(
text: 'EF',
style: smallTextStyle,
),
],
),
textAlign: TextAlign.center,
),
),
);
}
}
效果:
虽然我设置了 textAlign
为 center
,但是 AB CD EF 并未水平居中。
解决方案
嵌套 WidgetSpan
并设置 alignment
为 middle
:
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Text(
'CD',
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.w500,
color: Colors.blue,
),
),
),
最终效果:
当然,你也可以用 row
来实现。