Using RichText in Flutter: Guide and Examples

In Flutter, RichText is a widget that allows you to create text with different styles and formatting within a single text widget. You can use multiple TextSpan widgets to define different portions of the text with varying styles.

Here's an example of how to use RichText:

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('RichText Example'),
      ),
      body: Center(
        child: RichText(
          text: TextSpan(
            text: 'Hello ',
            style: DefaultTextStyle.of(context).style,
            children: <TextSpan>[
              TextSpan(
                text: 'Flutter',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.blue,
                ),
              ),
              TextSpan(text: ' is amazing!'),
            ],
          ),
        ),
      ),
    );
  }
}

In this example, the RichText widget is used to create a text with different styles. The TextSpan widgets are used as children to define the various portions of the text with distinct styles.

  • The first TextSpan is styled using the default text style of the context (in this case, it inherits the default style of the AppBar).
  • The second TextSpan applies a bold font weight and blue color to the word "Flutter."
  • The third TextSpan simply adds the text " is amazing!" to the end.

You can customize the formatting, fonts, colors, and other styles within each TextSpan as needed.

The RichText widget is particularly useful when you need to apply different styles to different portions of your text, such as when displaying formatted content or emphasizing specific words or phrases.

Feel free to experiment with different styles and nested TextSpan widgets to achieve the desired visual effects in your app.