How to Use the RichText Widget in Flutter

This article explains how to use the RichText widget in Flutter to style different parts of a sentence or individual words. The RichText widget enables the application of multiple text styles within a single string, which is helpful for creating visually distinctive text.

Example Overview

The example below demonstrates styling the phrase “The Flutter Dev”, where each word is given a different color. The first word is styled in red, the second in green, and the third in blue.

Using the RichText Widget

The RichText widget takes a list of TextSpan widgets, where each TextSpan represents a segment of text with its own styling. This allows for defining various styles for different portions of the text.

Full Code:

import 'package:flutter/material.dart';

class RichTextExample extends StatefulWidget {
  const RichTextExample({super.key});

  @override
  State<RichTextExample> createState() => _RichTextExampleState();
}

class _RichTextExampleState extends State<RichTextExample> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.orange,
        title: const Text(
          'Rich Text',
          style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
        ),
      ),
      body: Center(
        child: RichText(
          text: const TextSpan(children: [
            TextSpan(
                text: 'The ',
                style: TextStyle(
                    color: Colors.red,
                    fontSize: 36,
                    fontWeight: FontWeight.bold)),
            TextSpan(
                text: 'Flutter ',
                style: TextStyle(
                  color: Colors.green,
                  fontSize: 36,
                  fontWeight: FontWeight.bold,
                )),
            TextSpan(
                text: 'Dev',
                style: TextStyle(
                    color: Colors.blue,
                    fontSize: 36,
                    fontWeight: FontWeight.bold)),
          ]),
        ),
      ),
    );
  }
}
Dart

Code Explanation:

1. RichText Widget: Used to display text with multiple styles applied.
2. TextSpan Widgets: Each TextSpan widget defines a segment of text with its own style, such as
color, font size, and weight.
3. Custom Styles: The three words (“The”, “Flutter”, “Dev”) are styled with red, green, and blue colors,
respectively, with a font size of 36 and bold font weight.

Ouptut:

rich text flutter


Conclusion:

The RichText widget in Flutter provides a flexible way to create text with varied styles, making it suitable for situations where different text segments require distinct styling. This example demonstrates how RichText and TextSpan can be used to customize text appearance in a Flutter application.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top