字节笔记本

2026年3月22日

Flutter Text 文本及字体样式完全指南

这篇文章将详细介绍 Flutter 中 Text 组件的用法,包括 TextStyle 的所有属性、TextSpan 富文本、DefaultTextStyle 默认样式等,帮助开发者全面掌握 Flutter 文本渲染能力。

Text 组件

Text 组件用于显示文本,是 Flutter 中最基础的 UI 组件之一。

dart
Text(
  'Hello world',
  style: TextStyle(fontSize: 16),
);

Text 构造方法

dart
const Text(
  this.data, {
  Key key,
  this.style,
  this.strutStyle,
  this.textAlign,
  this.textDirection,
  this.locale,
  this.softWrap,
  this.overflow,
  this.textScaleFactor,
  this.maxLines,
  this.semanticsLabel,
  this.textWidthBasis,
}) : assert(
       data != null,
       'A non-null String must be provided to a Text widget.',
     ),
     textSpan = null,
     super(key: key);

属性说明

String data

要显示的文本内容,这是 Text 组件的必填参数。

TextStyle style

设置文本样式,包括颜色、字体大小、粗细等。TextStyle 是 Flutter 中控制文本外观的核心类。

属性说明
bool inherit是否继承父节点样式,默认为 true
Color color设置字体颜色,例:Colors.green
Color backgroundColor设置背景颜色
double fontSize设置字体大小
FontWeight fontWeight设置字体粗细:FontWeight.normal(默认,等同于 w400)、FontWeight.bold(加粗,等同于 w700)、FontWeight.w100 ~ FontWeight.w900
FontStyle fontStyle设置字体样式:FontStyle.normal(正常)、FontStyle.italic(斜体)
double letterSpacing字母间间距
double wordSpacing单词间间距
TextBaseline textBaseline对齐文本的水平线:TextBaseline.alphabeticTextBaseline.ideographic
double height文本行高
Locale locale根据地区以不同方式呈现
Paint foreground文本颜色,使用该属性时 color 需为 null,例:Paint()..color = Colors.red
Paint background文本背景色,使用该属性时 backgroundColor 需为 null
TextDecoration decoration文本装饰:TextDecoration.none(默认)、TextDecoration.lineThrough(删除线)、TextDecoration.underline(下划线)、TextDecoration.overline(上划线)
Color decorationColor控制装饰线的颜色
TextDecorationStyle decorationStyle控制装饰线的样式:TextDecorationStyle.solid(实线)、TextDecorationStyle.double(双线)、TextDecorationStyle.dotted(点线)、TextDecorationStyle.dashed(虚线)、TextDecorationStyle.wavy(波浪线)
double decorationThickness控制装饰线的粗细
String fontFamily设置文字字体
List<Shadow> shadows设置字体阴影,例:Shadow(color: Colors.black, offset: Offset(1.0, 1.0), blurRadius: 5.0)

StrutStyle strutStyle

StrutStyle 用于控制文本的最小行高和基线布局。它可以为文本设置一个" strut"(支柱),确保每一行至少达到指定的高度,即使某些行内容较小。

dart
Text(
  'Hello Flutter',
  strutStyle: StrutStyle(
    fontSize: 16,
    height: 1.5,
    leading: 0.5,
    fontWeight: FontWeight.w500,
  ),
);

TextAlign textAlign

文本的对齐方式:

说明
TextAlign.left左对齐(默认)
TextAlign.right右对齐
TextAlign.center居中对齐
TextAlign.justify两端对齐
TextAlign.start根据文本方向起始对齐
TextAlign.end根据文本方向末尾对齐

注意:只有在 Text 宽度大于文本内容长度时,textAlign 属性才有意义。

TextDirection textDirection

文本的书写方向:

说明
TextDirection.ltr从左到右
TextDirection.rtl从右到左

Locale locale

用于根据不同地区以不同方式呈现文本,如日期、数字等的本地化格式。

bool softWrap

是否自动换行。默认为 true。当设为 false 时,文本不会在容器边界处换行。

TextOverflow overflow

文本溢出时的处理方式:

说明
TextOverflow.clip直接裁剪(默认)
TextOverflow.fade渐变淡出
TextOverflow.ellipsis显示省略号
TextOverflow.visible可见溢出
dart
Text(
  '这是一段很长很长很长很长很长很长的文本内容,用于演示文本溢出效果',
  maxLines: 1,
  overflow: TextOverflow.ellipsis,
);

double textScaleFactor

文本的缩放因子,相对于字体大小的缩放比例。默认为 1.0

int maxLines

文本显示的最大行数。默认情况下文本自动折行,指定此参数后文本最多不会超过指定行数。

String semanticsLabel

用于语义化标签,提供给屏幕阅读器等辅助工具使用的文本描述。

TextWidthBasis textWidthBasis

控制文本宽度的计算方式:

说明
TextWidthBasis.parent根据父约束计算宽度
TextWidthBasis.longestLine根据最长行计算宽度

示例代码

dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Text 示例')),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 基本文本
              Text('Hello Flutter!'),

              // 设置样式
              Text(
                '带样式的文本',
                style: TextStyle(
                  fontSize: 24,
                  color: Colors.blue,
                  fontWeight: FontWeight.bold,
                ),
              ),

              // 带删除线
              Text(
                '删除线文本',
                style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  decorationColor: Colors.red,
                ),
              ),

              // 带下划线
              Text(
                '下划线文本',
                style: TextStyle(
                  decoration: TextDecoration.underline,
                  decorationStyle: TextDecorationStyle.dotted,
                ),
              ),

              // 文本溢出省略
              Container(
                width: 200,
                child: Text(
                  '这是一段很长的文本,超出容器宽度后会被截断显示省略号',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              // 居中对齐
              Container(
                width: 300,
                child: Text(
                  '居中对齐的文本',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 18),
                ),
              ),

              // 带阴影的文本
              Text(
                '带阴影的文本',
                style: TextStyle(
                  fontSize: 28,
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      color: Colors.black45,
                      offset: Offset(2, 2),
                      blurRadius: 4,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

TextSpan

TextSpan 用于创建富文本,可以在一段文本中混合使用不同的样式。它是 RichText 组件的核心,允许实现类似 HTML 中 <span> 标签的效果。

TextSpan 构造器

dart
const TextSpan({
  this.style,
  this.text,
  this.children,
  this.recognizer,
  this.semanticsLabel,
});

TextSpan 属性说明

属性说明
TextStyle style文本样式
String text显示的文本内容
List<TextSpan> children子 TextSpan 列表
GestureRecognizer recognizer手势识别器,用于点击事件等
String semanticsLabel语义化标签

TextSpan 使用示例

dart
Text.rich(
  TextSpan(
    text: '你好,',
    style: TextStyle(fontSize: 20, color: Colors.black),
    children: <TextSpan>[
      TextSpan(
        text: 'Flutter',
        style: TextStyle(
          fontSize: 24,
          color: Colors.blue,
          fontWeight: FontWeight.bold,
        ),
      ),
      TextSpan(
        text: '!这是一段',
        style: TextStyle(fontSize: 20),
      ),
      TextSpan(
        text: '富文本',
        style: TextStyle(
          fontSize: 22,
          color: Colors.red,
          decoration: TextDecoration.underline,
        ),
      ),
      TextSpan(text: '示例。'),
    ],
  ),
);

带点击事件的 TextSpan

dart
Text.rich(
  TextSpan(
    text: '请阅读并同意我们的',
    style: TextStyle(fontSize: 14),
    children: <TextSpan>[
      TextSpan(
        text: '服务条款',
        style: TextStyle(
          color: Colors.blue,
          decoration: TextDecoration.underline,
        ),
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            print('点击了服务条款');
          },
      ),
      TextSpan(text: '和'),
      TextSpan(
        text: '隐私政策',
        style: TextStyle(
          color: Colors.blue,
          decoration: TextDecoration.underline,
        ),
        recognizer: TapGestureRecognizer()
          ..onTap = () {
            print('点击了隐私政策');
          },
      ),
    ],
  ),
);

注意:使用 GestureRecognizer 时需要在组件销毁时调用 dispose() 方法释放资源。

DefaultTextStyle

DefaultTextStyle 是 Flutter 中用于设置默认文本样式的组件。它的子树中所有 Text 组件如果没有显式指定 style,就会继承 DefaultTextStyle 的样式。

DefaultTextStyle 构造器

dart
const DefaultTextStyle({
  Key key,
  @required this.style,
  this.textAlign,
  this.softWrap,
  this.overflow,
  this.maxLines,
  this.textWidthBasis,
  this.textHeightBehavior,
  Widget child,
});

属性说明

属性说明
TextStyle style默认的文本样式
TextAlign textAlign默认的文本对齐方式
bool softWrap默认是否自动换行
TextOverflow overflow默认的溢出处理方式
int maxLines默认的最大行数
TextWidthBasis textWidthBasis默认的宽度计算方式
Widget child子组件

使用示例

dart
DefaultTextStyle(
  style: TextStyle(
    fontSize: 16,
    color: Colors.grey[600],
  ),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      // 这个 Text 会继承 DefaultTextStyle 的样式
      Text('继承默认样式的文本'),

      // 这个 Text 用自己的样式覆盖默认样式
      Text(
        '自定义样式的文本',
        style: TextStyle(
          fontSize: 20,
          color: Colors.red,
          fontWeight: FontWeight.bold,
        ),
      ),

      // 这个 Text 也会继承默认样式
      // 但可以通过 inherit: false 完全使用自己的样式
      Text(
        '不继承默认样式的文本',
        style: TextStyle(
          inherit: false,
          fontSize: 14,
          color: Colors.green,
        ),
      ),
    ],
  ),
);

关键点:当 TextStyle.inherittrue(默认值)时,显式设置的样式会与 DefaultTextStyle 合并;当设为 false 时,将完全使用自己的样式,不进行任何合并。

DefaultTextStyle.merge

如果只想覆盖默认样式的部分属性,可以使用 DefaultTextStyle.merge

dart
DefaultTextStyle.merge(
  style: TextStyle(color: Colors.red),
  child: Text('只修改颜色,其他继承'),
);
分享: