Flutter TextSpan 组件使用详解

62 min read

TextSpan 是 Flutter 中的文本组件,它可以在单个标签内创建具有不同样式的文本。TextSpan 组件具有以下属性:

  • text:设置文本内容。
  • style:设置文本样式,如颜色、字体大小、粗体等,使用 TextStyle 组件。
  • children:可以包含其他 TextSpan 或 Widget 组件,使其形成一个文本树。

使用 TextSpan 组件的步骤如下:

  1. 导入 TextSpan 组件和 TextStyle 组件。
import 'package:flutter/material.dart';
  1. 创建 TextSpan 组件。
TextSpan(
  text: 'Hello',
  style: TextStyle(
    color: Colors.red,
    fontWeight: FontWeight.bold,
  ),
)
  1. 在 Text 组件中使用 TextSpan 组件。
Text.rich(
  TextSpan(
    text: 'Hello',
    style: TextStyle(
      color: Colors.red,
      fontWeight: FontWeight.bold,
    ),
  ),
)

完整示例:

import 'package:flutter/material.dart';

class TextSpanDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text.rich(
          TextSpan(
            text: 'Hello',
            style: TextStyle(
              color: Colors.red,
              fontWeight: FontWeight.bold,
            ),
            children: [
              TextSpan(
                text: ' World',
                style: TextStyle(
                  color: Colors.blue,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

运行效果如下图所示:

textspan_demo

常见用法是将 TextSpan 作为 TextField 组件的 decoration 属性的值,这样可以为输入框的 label 或者 hint 添加丰富的样式。例如:

TextFormField(
  decoration: InputDecoration(
    labelText: 'Username or Email',
    labelStyle: TextStyle(
      fontSize: 18,
      fontWeight: FontWeight.bold,
      color: Colors.grey[600],
    ),
    hintText: 'Enter your username or email',
    hintStyle: TextStyle(
      fontSize: 14,
      color: Colors.grey[400],
    ),
    prefixIcon: Icon(Icons.person),
    border: OutlineInputBorder(),
  ),
);

完整示例:

import 'package:flutter/material.dart';

class TextFormFieldDemo extends StatelessWidget {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextFormField Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Username or Email',
                  labelStyle: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey[600],
                  ),
                  hintText: 'Enter your username or email',
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[400],
                  ),
                  prefixIcon: Icon(Icons.person),
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your username or email';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Form submitted')),
                    );
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

运行效果如下图所示:

textformfield_demo