Using TextSpan in Flutter: Guide and Examples

Using TextSpan in Flutter, you can create rich text by applying different formatting attributes to various portions of the text. It allows you to create text with different styles, colors, fonts, and more. TextSpan is utilized within both the Text and RichText widgets to achieve richly formatted text.

Here's an example of how to use TextSpan within the Text widget:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextSpan Example'),
      ),
      body: Center(
        child: Text.rich(
          TextSpan(
            text: 'Hello ',
            style: TextStyle(fontSize: 20),
            children: [
              TextSpan(
                text: 'Flutter',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                ),
              ),
              TextSpan(text: '!'),
            ],
          ),
        ),
      ),
    );
  }
}

In this example, we use Text.rich to create a Text widget with a TextSpan. TextSpan enables us to create multiple different text spans within a Text widget, each with its own styling attributes such as font, color, and formatting.

TextSpan can also be used within the RichText widget to achieve more advanced text formatting capabilities. You're free to create and combine multiple TextSpan instances to craft richly formatted text as desired.

I hope this example helps you understand how to use TextSpan in Flutter.