Flutter Analysis and Practice: RichText Best Practices

2.4.1 How RichText Works

Figure 2–14
  • Create a LeafRenderObjectElement instance.
  • The ComponentElement method calls the CreateRenderObject method of the RichText instance to generate the RenderParagraph instance.
  • The RenderParagraph instance creates a TextPainter, which is a proxy class responsible for width and height calculation and text-to-canvas rendering. In addition, TextPainter also has a TextSpan text structure.
Figure 2–15

2.4.2 Design

Figure 2–16
/// The amount of space (in logical pixels) to add between each letter
/// A negative value can be used to bring the letters closer.
final double letterSpacing;
/// Returns the offset at which to paint the caret.
/// Valid only after [layout] has been called.
Offset getOffsetForCaret(TextPosition position, Rect caretPrototype)

2.4.3 Key Code Implementation

  • Unified placeholder SpaceSpans.
GestureRecognizer recognizer,
}) : super(
style: TextStyle(
color: Colors.transparent,
letterSpacing: contentWidth,
height: 1.0,
text: '\u200B',
recognizer: recognizer);
  • Acquisition of SpaceSpan relative positions.
for (TextSpan textSpan in widget.text.children) {
if (textSpan is SpaceSpan) {
final SpaceSpan targetSpan = textSpan;
Offset offsetForCaret = painter.getOffsetForCaret(
TextPosition(offset: textIndex),
0.0, targetSpan.contentHeight, targetSpan.contentWidth, 0.0),
textIndex += textSpan.toPlainText().length;
  • Integration of RichText and SpaceSpans.
children: <Widget>[
Positioned(left: position.dx, top: position.dy, child: child),

2.4.4 Results

Figure 2–17

Original Source:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com