Sub topic 1
Showing text with the Text widget
The Text widget draws a string on screen. Almost every Flutter screen uses it, so its defaults and failure modes are worth knowing before you style anything. This chapter covers how Text is constructed, where its appearance comes from when you set nothing, and the mistakes that most often cause errors.
Prerequisites
This chapter assumes you have the following:
- Basic Dart syntax, including classes, named parameters, and string interpolation.
- Familiarity with
StatelessWidgetand thebuildmethod. - A Flutter project that runs on an emulator, a device, or the web.
Styling, alignment, theme text styles, Text.rich, fonts, and text scaling each get their own chapter. Here they appear only as pointers.
The smallest working example
The constructor Text(String data) takes one positional argument, the string to display. Everything else is a named, optional parameter. This complete app shows one line of text in the center of the screen:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Text('Hello, Flutter'),
),
),
);
}
}Use const whenever the string is a literal. A const Text is created once and reused, so Flutter can skip rebuilding it. When the string depends on a variable, drop const from that widget.
Where the default look comes from
You passed no style, yet the text is black, about 14 logical pixels tall, and set in the platform's default font. A Text with no style inherits one from the nearest DefaultTextStyle above it in the widget tree. When you do pass a style, Flutter merges it over that inherited style. Any property you leave unset keeps the inherited value.
MaterialApp, Scaffold, and Material all provide a sensible DefaultTextStyle. If a Text sits outside any of them, Flutter uses a loud fallback: red text with a yellow double underline. That fallback means you forgot a Scaffold or Material ancestor, and the fix is to add one. It doesn't mean you need to style the text.
Building strings
The data argument is an ordinary Dart String, so all Dart string features work.
import 'package:flutter/material.dart';
class OrderSummary extends StatelessWidget {
const OrderSummary({super.key, required this.name, required this.count});
final String name;
final int count;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Hello, $name'),
Text('Items: $count'),
Text('Total: \$${(count * 4.5).toStringAsFixed(2)}'),
const Text('Line one\nLine two'),
],
);
}
}A few details in this example matter:
$nameand${...}interpolate values. Escape a literal dollar sign as\$, or use a raw string such asr'$5'.\nstarts a new line inside a singleText. The widget lays out all lines as one block.Textaccepts only aString.Text(count)does not compile, so use interpolation orcount.toString().
Nullable values
Text(null) is a compile error under null safety. When a value may be missing, decide what the user should see instead of passing it through:
Text(user.nickname ?? 'Anonymous')If you want nothing at all when the value is null, don't build the widget. Inside a list literal, use a collection if:
children: [
if (subtitle != null) Text(subtitle!),
],Passing an empty string Text('') still creates a widget. It has zero width but occupies a line's height in a Column, which can leave an unexpected gap.
Constructor parameters at a glance
Text has many optional parameters. This table lists the ones you meet most, and the chapters that cover them.
| Parameter | What it controls | Covered in |
|---|---|---|
| `style` | Size, weight, color, spacing | Styling text with TextStyle |
| `textAlign` | Horizontal alignment of lines within the widget's width | Alignment, wrapping, and overflow |
| `maxLines` | Maximum number of lines before truncation | Alignment, wrapping, and overflow |
| `overflow` | What to do with text that does not fit | Alignment, wrapping, and overflow |
| `softWrap` | Whether long lines break at word boundaries | Alignment, wrapping, and overflow |
| `textScaler` | Scaling relative to the user's font setting | Text scaling and user font settings |
| `semanticsLabel` | Text that screen readers announce instead of the string | Making text, images, and icons accessible |
You can leave all of them unset and get sensible behavior. The defaults wrap text onto as many lines as the available width requires, with no limit on line count.
Text and the size of its box
A Text takes only as much space as its string needs, up to the width its parent allows. Two consequences follow:
- In a
ColumnorCenter, the widget shrinks to fit the text. SettingtextAlignthere has little visible effect, because the box is exactly as wide as the longest line. - In a
Row, a long string is not told to wrap. It asks for its full width, and when that exceeds the available space, Flutter paints a yellow and black overflow stripe and logs aRenderFlex overflowederror.
The usual remedy for the second case is to wrap the Text in Expanded or Flexible, so the row gives it a bounded width and the string wraps. The layout chapter that follows treats this in detail.
Selectable text
Text drawn by Text cannot be selected or copied by default. There are two ways to change this:
SelectableText('Order #1042')replacesTextfor a single selectable string.SelectionAreawraps a whole subtree and makes everyTextinside it selectable, with one shared selection across widgets.
Prefer SelectionArea when users should be able to select across several paragraphs. Use SelectableText for isolated values such as an order number.
Common errors
- Red text with yellow underlines. The
Texthas noMaterialorDefaultTextStyleancestor. Wrap the screen in aScaffold. The argument type 'int' can't be assigned to 'String'. Convert the value with interpolation.Text(null)or a nullable variable won't compile. Supply a fallback with??, or omit the widget with a collectionif.RenderFlex overflowedfor a long string in aRow. Give theTextbounded width withExpanded.consterrors.const Text('Hi $name')fails becausenameis not a compile-time constant. Removeconst.- Literal
$missing from output. Escape it as\$.
Exercise
A screen shows Text('Price: $price') where price is a double? that may be null. The screen currently prints "Price: null" when no price exists. How would you change it so that the line does not appear at all when price is null, and shows two decimal places otherwise? Name where it must go and why const cannot be used.
Show answer
Put a collection if in the parent's children list: if (price != null) Text('Price: ${price!.toStringAsFixed(2)}'). The widget is only built when a price exists, so nothing is drawn otherwise. The string depends on the runtime variable price, which is not a compile-time constant, so const cannot be applied to this Text.