Rich Typewriter: Animating Text with a Typewriter Effect in Flutter

Published on by Flutter News Hub

Rich Typewriter: Animating Text with a Typewriter Effect in Flutter

Rich Typewriter is a Flutter widget that enables you to animate Text.rich or RichText elements like a typewriter. It supports complex text trees with InlineSpan elements of any depth, including WidgetSpans for embedding widgets within the text.

Motivation

The need for Rich Typewriter arose when creating a visual novel engine. Existing solutions for animating rich text either lacked compatibility with existing RichTexts or did not support WidgetSpans.

Features

  • Animates Text.rich or RichText elements.
  • Supports multi-level InlineSpan trees.
  • Handles both text characters and widgets.
  • Customizable delays for each character or widget.
  • End-of-animation callback.

Usage

To use Rich Typewriter, simply wrap your Text.rich or RichText widget with it, as shown in this example:

RichTypewriter(
  child: const Text.rich(
    TextSpan(
      text: "some text",
      children: [
        WidgetSpan(
          child: FlutterLogo(
            size: 100,
          ),
        ),
      ],
    ),
  ),
);

Customization

You can customize the animation by setting the following properties:

  • cursorDelay: Delay between displaying characters (default: Duration(milliseconds: 50)).
  • widgetDelay: Delay between displaying widgets (default: Duration(milliseconds: 100)).
  • onEnd: Function to be called when the animation completes.

Example

This code example demonstrates how to use Rich Typewriter with custom delays and an end-of-animation callback:

RichTypewriter(
  cursorDelay: const Duration(milliseconds: 20),
  widgetDelay: const Duration(milliseconds: 50),
  onEnd: () {
    print("Animation completed!");
  },
  child: const Text.rich(
    TextSpan(
      text: "Hello",
      children: [
        WidgetSpan(
          child: Image.network("https://example.com/image.png"),
        ),
      ],
    ),
  ),
);

Conclusion

Rich Typewriter provides a convenient way to add typewriter-style animations to your Flutter applications. It supports complex text trees, including widgets, and allows for customization of the animation behavior.

Flutter News Hub