Since Flutter only supports horizontal text layouts, I’ve had to do a lot of digging into the source code of its text rendering system as I create vertical text widgets for traditional Mongolian. In this article I’ll share what I’ve discovered about how text editing widgets work in Flutter.

Before diving into that, though, let’s first review how the Text widget works.

Text rendering

Usually all we see of the Text widget is something like this:

Text(
  'Hello world',
  style: TextStyle(fontSize: 30),
),

However, there are many layers below that.

Widgets layer

When you use a Text widget, what it actually creates is a RichText widget.

Image for post

Unlike Text, which takes a String as the data parameter, RichText takes a TextSpan (or more precisely an InlineSpan, but more on that in a minute). A TextSpan needs both a String and a TextStyle, so before Text can create RichText it takes whatever TextStyle you gives it and combines that with the app default TextStyle, which Text gets from its BuildContext. Here is a more detailed version of the image above:

Image for post

Since Text only takes a single string and style as a parameter, the entire string that it gives in the TextSpan to RichText will have only one single style. The TextSpan class is interesting, though, because like a multi-child widget, it can take more text spans as children. That means you can use it to build a whole tree of text spans, where each node potentially has a string and a style.

Image for post

That’s hard to reason about, though, so you usually just have a single parent TextSpan with a bunch of children.

Image for post

This you can pass in to the Text.rich constructor or directly to the RichText widget. If you pass it directly to the RichText widget, though, the style won’t get combined with the default style from the build context.

Read Mastering Styled Text in Flutter for practical examples of using a TextSpan to style text.

RichText itself is a subclass of MultiChildRenderObjectWidget. The reason that RichText has multiple children internally is that you can intersperse other widgets in a line of text. The images above showed a TextSpan tree, but actually RichText takes an InlineSpan, where an InlineSpan can be either a TextSpan or a WidgetSpan. For the purposes of this article, I’ll only deal with TextSpans.

#flutter #mobile-apps #programming #developer #web-development

How Text Editing Works Internally in Flutter
1.85 GEEK