iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📜

Understanding the Text Widget in Flutter

に公開

This article is for Day 12 of the Flutter #3 Advent Calendar 2020 - Qiita.


If you have developed Flutter apps, I believe there is no one who hasn't used Text. It's that ubiquitous widget you always use when you want to display characters on the screen.

Usage is extremely simple:

const Text('Hello, Flutter!');

By just writing this, the text Hello, Flutter! appears on the screen.

While everyone uses this Text widget, have you ever actually read its API documentation or source code?

In this article, we will explore what is written in the Flutter documentation and how to navigate the source code by reading through the Text widget's docs and code. The goal is to enable you to investigate and deepen your understanding of other frequently used widgets—such as Container or Row—whenever necessary during development.

Note: For those who already develop while routinely reading official documentation and source code, most of this content may feel elementary. I appreciate your understanding.

Recommended Reading

https://api.flutter.dev/flutter/widgets/Text-class.html

This is the API documentation for Text. This article follows this documentation, but since some parts might be omitted or mistranslated here, it's a good idea to read the full text yourself once you have a general understanding from this article. It's not a very long document, so there's no need to feel intimidated.

https://zenn.dev/chooyan/articles/77a2ba6b02dd4f

This is an article I wrote recently to help understand Flutter's "Three Trees."
Since it covers the foundational concepts for understanding the structure of various widgets (including Text) and how Flutter works, please give it a read if you're interested. It is a bit long (and the references are even longer), so I recommend reading it slowly during the year-end holidays.

Main Content

Reading the API Documentation

First, let's read the Text documentation from the top. I'll proceed by quoting sections at logical breaking points, providing a translation, and adding further explanations.

What is Text?

At the very beginning of the documentation, the "What is it?" information is provided. For the Text documentation, it is described as follows:

The Text widget displays a string of text with single style.

Translation: The Text widget displays a string of text with a single style.

This kind of "What is it?" explanation is very important. Depending on the tool, information like "how to write it to get a certain result" might spread through technical articles ahead of "what it actually is." However, that might only explain one side of the object and could potentially deviate from its intended use. Therefore, to grasp the first principles, it is vital to understand in one sentence what the widget "is."

Now, the explanation for "What is Text?" is as above, and it likely matches your current understanding. It's something that displays text on the screen. It also explicitly states that, basically, the style is uniform for the entire text.

After reading this, you might wonder, "Then what happens if I want to change the style for specific parts of the text, like Twitter hashtags?" That explanation will appear later, so let's move forward for now.

Text Wrapping

Following the "What is it?" explanation, descriptions of Text's properties are provided for each topic. First is the content about line breaks.

The string might break across multiple lines or might all be displayed on the same line depending on the layout constraints.

Translation: The specified string may be broken into multiple lines or displayed on a single line depending on the layout constraints.

layout constraints are also explained in "Inside Flutter". In the RenderObject tree, these are data passed from parent to child as constraints that determine the layout, which the child considers when calculating its layout.

The wrapping constraints explained here seem to follow rules such as: if softWrap is true or overflow is TextOverflow.ellipsis, and maxLines is not specified, it will be displayed on only one line. [1]

About Style

Next, the documentation moves on to text styling.

The style argument is optional. When omitted, the text will use the style from the closest enclosing DefaultTextStyle.

Translation: The style argument is optional. If omitted, it will use the nearest DefaultTextStyle.

This is likely as you understand it, but it is good to remember that if nothing is specified, DefaultTextStyle will be used. For example, the reason why Text looks significantly different when displayed in a place not enclosed by a Scaffold is that this DefaultTextStyle is not the one created by Scaffold, but the one created by MaterialApp (more accurately, the WidgetApp within it).

If you understand the concept of InheritedWidget, "closest" should be easy to visualize [2]. Since DefaultTextStyle inherits from InheritedWidget, descendant Widgets can reference the DefaultTextStyle existing in their ancestors in the Widget tree via their Elements.

Furthermore, when referencing an InheritedWidget through an Element, if multiple subclasses of the same type (in this case, DefaultTextStyle) exist, the specification is to overwrite with the most recent one. Because of this specification, the explanation says, "use the closest enclosing DefaultTextStyle."

In this way, if you understand the underlying knowledge like the "Three Trees" beforehand, and can also understand "why" the content described in the documentation is the way it is, the internal structure will become much easier to visualize.

Now, reading further:

If the given style's TextStyle.inherit property is true (the default), the given style will be merged with the closest enclosing DefaultTextStyle. This merging behavior is useful, for example, to make the text bold while using the default font family and size.

Translation: If the TextStyle.inherit property of the specified style is true (the default), that style will be merged with the nearest DefaultTextStyle. This is useful, for example, when you want to keep the default font and size but only make the text bold.

You can see this by looking at the implementation of Text.build.

if (style == null || style.inherit)
  effectiveTextStyle = defaultTextStyle.style.merge(style);

As users of the Text widget, we usually specify a TextStyle in the style property when we want to set the text style. Internally, however, the specified TextStyle is merged with the nearest DefaultTextStyle using TextStyle.merge.

Conversely, we can infer from this that if we want to specify a style while completely ignoring the DefaultTextStyle, we can just set inherit of the TextStyle to false. Aside from the specific method, keeping in mind that "such a thing is possible" can be useful later, and the documentation contains many such details.

Following this, there are code samples for the user, but I will omit those in this article.

About Text.rich

You might almost miss it among the code samples, but the explanation for "changing the style for specific parts of the text" mentioned earlier is described here.

Using the Text.rich constructor, the Text widget can display a paragraph with differently styled TextSpans.

Translation: By using the Text.rich constructor, the Text widget can display multiple TextSpans with different styles as a single block of text.

As mentioned before, the Text widget basically displays text with a single style. On the other hand, it is noted here that if you want to change the style for each character or section, you should use Text.rich and provide TextSpan as its argument.

TextSpan has a text property representing the string to display, a style property for the styling, and a children property for child elements. By specifying multiple TextSpans in this children property, you can connect and display multiple strings with different styles. For specific usage, please read the samples that follow it.

Reacting to Touch

Following the sample code, the content continues with the title "Interactivity." This is about how to make the text react to user touch operations.

To make Text react to touch events, wrap it in a GestureDetector widget with a GestureDetector.onTap handler.

Translation: To make Text respond to touch events, wrap it in a GestureDetector widget with a GestureDetector.onTap handler.

In a material design application, consider using a TextButton instead, or if that isn't appropriate, at least using an InkWell instead of GestureDetector.

Translation: In a Material Design application, consider using a TextButton instead. If a TextButton is not appropriate, at least use an InkWell instead of a GestureDetector.

According to this, while you can respond to touch operations by wrapping the Text in a GestureDetector, it is recommended [3] to use a TextButton when using MaterialApp. The next best option is to wrap the Text in an InkWell. This is likely a design-related recommendation, as a GestureDetector won't show the ripple effect or provide that "pressable" feel.

Being able to learn about these "official recommendations" is another advantage of reading the official documentation. [4]

To make sections of the text interactive, use RichText and specify a TapGestureRecognizer as the TextSpan.recognizer of the relevant part of the text.

Translation: To make parts of the text interactive, use RichText and specify a TapGestureRecognizer as the TextSpan.recognizer for the relevant portion of the text.

As stated, by using RichText, you can not only change the style of specific parts of the text but also set touch events for just those parts. Using this, you can implement features such as making hashtags or URLs within the text tappable.


With this, we have finished reading the introductory explanations. What follows are definitions for related classes, constructors, and methods, but I will omit those in this article.

Let's Read the Source Code

Having read the documentation, next I would like to read excerpts from the source code.

The source code is the "actually running program itself." While documentation might be slightly abstract or omit certain details for the sake of verbal explanation, reading the program allows you to obtain information that can definitively be called the "correct answer." Although it takes effort to read, doing so as much as possible should lead to a more accurate understanding.

StatelessWidget and build()

When investigating Flutter widget-related classes in particular, the class definition—especially the inheritance relationship—is very important. This is because the role and structure differ completely depending on whether the parent class is a StatelessWidget, a RenderObjectWidget, or an InheritedWidget.

In the case of Text:

class Text extends StatelessWidget {

Thus, it is a class that inherits from StatelessWidget. Like the widgets we app developers often create, StatelessWidget constructs its children and the widgets below them using the build() method. Let's look at the relevant part of the source code.

@override
Widget build(BuildContext context) {
  final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
  TextStyle? effectiveTextStyle = style;
  if (style == null || style!.inherit)
    effectiveTextStyle = defaultTextStyle.style.merge(style);
  if (MediaQuery.boldTextOverride(context))
    effectiveTextStyle = effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold));
  Widget result = RichText(
    textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
    textDirection: textDirection, 
    // ..omitted..
  );
  if (semanticsLabel != null) {
    result = Semantics(
      textDirection: textDirection,
      label: semanticsLabel,
      child: ExcludeSemantics(
        child: result,
      ),
    );
  }
  return result;
}

The build() method ultimately returns (i.e., makes its child widget) the result variable. Looking at the middle of the code above (partially omitted), you can see that it assigns a RichText widget.

RichText is a widget that acts like an extended version of Text, allowing you to change colors or decorations for specific parts of the text or add touch events. From this, we can see that a more accurate mental model is that Text is a widget designed to make a subset of RichText's features easier to use.

The build() method doesn't just generate a RichText. Before that, it performs the process mentioned earlier:

If the given style's TextStyle.inherit property is true (the default), the given style will be merged with the closest enclosing DefaultTextStyle.

Furthermore, in the lines after generating the RichText, if a semanticLabel is specified, it wraps the RichText in Semantics and ExcludeSemantics widgets.

Since the role of a StatelessWidget or StatefulWidget is to flexibly assemble the widget tree structure based on the content of specified properties [5], we can see that this Text widget also makes good use of that mechanism.

Text.rich Constructor

As mentioned in the documentation, Text provides a constructor called Text.rich.

const Text.rich(
  InlineSpan this.textSpan, {
  Key? key,
  this.style,
  ..omitted..
}) : assert(
       textSpan != null,
       'A non-null TextSpan must be provided to a Text.rich widget.',
     ),
     data = null,
     super(key: key);

Text.rich is a constructor for creating a widget that partially decorates text. Since RichText serves a similar role, it's easy to get confused about which one to use, but as we saw earlier, both internally generate a RichText widget.

However, considering that Text.rich properly handles style merging and wrapping with Semantics within its build() method, it's generally better to use the Text.rich constructor when you want to create "partially decorated text."

If you tried to do the same thing with RichText, you would have to write code to manually specify the DefaultTextStyle in the TextSpan's style (just as Text.build does) and similarly write code to wrap it with Semantics and ExcludeSemantics. The RichText documentation also states the following:

Consider using the Text widget to integrate with the DefaultTextStyle automatically. When all the text uses the same style, the default constructor is less verbose. The Text.rich constructor allows you to style multiple spans with the default text style while still allowing specified styles per span.

Translation: Consider using the Text widget to automatically apply DefaultTextStyle. If the entire text uses the same style, the default constructor is simpler than RichText. By using the Text.rich constructor, you can apply specific styles to parts of the text while applying the default style to the rest.

This isn't everything, but by reading the source code, you can make discoveries like this. For example, when faced with the question "Should I use RichText or Text.rich?", you can make an appropriate judgment based on a code-level comparison.

Summary

In this article, we've taken a quick look at the documentation and source code for Text.

While Text is something we use every day as a matter of course, investigating it again revealed several new things: it uses RichText internally, using Text.rich is more appropriate than using RichText directly due to style and Semantics handling, and new widgets like TextButton (along with related OverflowedText and OutlinedText) have been recently added as tappable Text options.

Additionally, since there are many other widgets in Flutter created as subclasses of StatelessWidget (just like the widgets we build), I feel that reading the code for these widgets can provide various technical references for how to build StatelessWidgets and StatefulWidgets.

Code for things like Text can be read immediately using the "Go to Definition" feature of your IDE (Command + Click in VSCode on Mac), so casually reading through other classes during development can be very educational.

While technical articles by individual developers like this one are great as a starting point for research, I believe that by verifying information with official documentation and source code as much as possible, you can make your understanding more accurate and implement the best solutions according to requirements in your development.

脚注
  1. I couldn't trace the exact location in the source code, so this is just based on how it seemed to behave during my operation check... ↩︎

  2. Regarding InheritedWidget, please also refer to "【Flutter】What is InheritedWidget". ↩︎

  3. TextButton seems to be a widget added in Flutter 1.22. ↩︎

  4. It would be even better if they explained "why" it's recommended, but it seems they didn't write that this time. ↩︎

  5. Subclasses of RenderObjectWidget like RichText do not have a build() method; they only have immutable child (or children) fields, meaning they are not structured to flexibly change child or children depending on conditions. ↩︎

Discussion