Sub topic 1
Showing text with the Text widget
Prerequisites
This chapter assumes you know Dart classes and named parameters, and that you understand StatelessWidget and the build method. You need a Flutter project that runs on an emulator, a device, or the web.
Displaying text
The Text widget draws a string on the screen. Pass the string as the first argument. The example below styles the text with the theme, then limits it to one line.
import 'package:flutter/material.dart';
class Greeting extends StatelessWidget {
const Greeting({super.key});
@override
Widget build(BuildContext context) {
return Text(
'Hello, Flutter',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
}Styling text with TextStyle
The style parameter takes a TextStyle. A TextStyle sets font size, weight, color, and letter spacing. The copyWith method returns a new style with only the fields you name changed. The original style does not change.
Alignment, wrapping, and overflow
textAlign sets horizontal alignment. maxLines caps the number of lines. overflow decides what happens to text that does not fit. TextOverflow.ellipsis adds "...", and TextOverflow.fade fades the end of the text.
Using theme text styles
Theme.of(context).textTheme holds named styles such as headlineMedium and bodyLarge. Use these styles instead of hard-coded sizes. Then all text in the app updates when the theme changes. The ? operator is needed because each slot can be null.
Mixing styles with Text.rich
Text.rich accepts a tree of TextSpan objects. Each child span inherits its parent's style unless it sets its own. This lets one paragraph contain bold and plain parts.
const Text.rich(
TextSpan(
text: 'Total: ',
children: [
TextSpan(
text: 'USD 42',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
)Exercise
A label must show one line, and any extra characters must end in "...". Which two parameters do you set on Text, and what values do they take?
Show answer
Set maxLines: 1 and overflow: TextOverflow.ellipsis.