Flutter 零基础入门(二十二):Text 文本组件与样式系统
在上一篇中,我们学习了:
- Container 的使用
- padding / margin
- BoxDecoration(圆角、阴影、边框)
页面已经开始"好看"了。
而这一篇,我们要解决 UI 中出现频率最高的问题:
文字怎么显示?怎么变好看?
一、Text 是什么?
在 Flutter 中:
Text 用来显示一段文本内容
几乎所有页面都会使用 Text。
二、最简单的 Text
dart
Text('Hello Flutter')
这是一段:
- 默认字号
- 默认颜色
- 单行文本
三、Text 的常用属性(核心)
1️⃣ style:文字样式
Text(
'Hello Flutter',
style: TextStyle(
fontSize: 18,
color: Colors.blue,
),
)
2️⃣ fontSize:字号
fontSize: 16
一般建议:
- 正文:14 ~ 16
- 标题:18 ~ 24
3️⃣ color:文字颜色
color: Colors.red
4️⃣ fontWeight:粗细
fontWeight: FontWeight.bold
常见值:
- w400(正常)
- w500 / w600(偏粗)
- bold
四、TextStyle 的独立使用(推荐)
❌ 不推荐
Text(
'标题',
style: TextStyle(fontSize: 18),
)
✅ 推荐
final titleStyle = TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
);
Text('标题', style: titleStyle);
📌 样式复用是专业 Flutter 项目的标志
五、行数限制与溢出(重点)
1️⃣ maxLines
Text(
'这是一段很长很长的文本',
maxLines: 2,
)
2️⃣ overflow
Text(
'这是一段很长很长的文本',
maxLines: 1,
overflow: TextOverflow.ellipsis,
)
效果:
这是一段很长的...
3️⃣ 常见溢出方式
- clip(裁剪)
- fade(渐隐)
- ellipsis(省略号,最常用)
六、textAlign:文本对齐
Text(
'Hello Flutter',
textAlign: TextAlign.center,
)
常见值:
- left
- center
- right
七、Text 与 Row / Column 的组合
常见错误 ❌
Row(
children: [
Text('很长很长很长的文本'),
Icon(Icons.arrow_forward),
],
)
可能导致溢出。
正确写法 ✅
Row(
children: [
Expanded(
child: Text(
'很长很长很长的文本',
overflow: TextOverflow.ellipsis,
),
),
Icon(Icons.arrow_forward),
],
)
八、富文本(简单了解)
Text.rich(
TextSpan(
children: [
TextSpan(text: '价格:'),
TextSpan(
text: '¥99',
style: TextStyle(color: Colors.red),
),
],
),
)
用于:
- 强调局部文字
- 价格、关键词高亮
九、实战:一个标准列表项文字结构
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'这是标题',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 4),
Text(
'这是描述内容,最多显示两行,超出显示省略号。',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
],
)
十、新手常见误区
❌ 不限制 maxLines
❌ Row 中直接放长文本
❌ 样式到处复制
❌ 字号、颜色随意写
📌 建议:
统一 TextStyle,比写 100 行布局都重要
十一、这一篇你真正学会了什么?
你已经掌握了:
- Text 的常用属性
- TextStyle 的使用与复用
- 文本溢出的处理方式
- Flutter 中专业文本写法
你现在写的文字:
已经像"正式 App"而不是 Demo 了
十二、总结
本篇你学会了:
- Text 的基本与进阶用法
- 文本样式系统
- 实战级文字布局技巧
🔜 下一篇预告
《Flutter 零基础入门(二十三):Icon、Image 与资源管理》
下一篇我们将学习:
- Icon 的使用
- Image 加载本地与网络图片
- pubspec.yaml 中的资源配置
- 常见图片加载坑点
从下一篇开始:
你的 App 将"真正有图有内容" 🖼️