What is the Text Widget?
The Text widget is one of the most fundamental widgets in Flutter. It displays a string of text with a single style. You can customize its appearance using the style property, control alignment, handle overflow, and more. The Text widget is lightweight and used everywhere – from app bars to buttons to long paragraphs.
Basic Usage
This will display the string with the default theme's text style (usually the bodyMedium style).
Styling Text with TextStyle
The style property takes a TextStyle object that can define font size, weight, color, decoration, font family, and more.
Text Alignment
Use textAlign to control how the text is aligned within its parent. The available values are: TextAlign.left, right, center, justify, start, end. The default depends on the text direction.
For textAlign to have an effect, the widget's parent must provide enough width (e.g., a Container with a width, or a SizedBox). In a Column, the text may not be centered horizontally unless the parent is constrained.
Handling Text Overflow
When text exceeds the available space, you can control the overflow behavior using the overflow property. Common values:
TextOverflow.clip– cuts off the text at the edge.
TextOverflow.ellipsis– adds…at the end.
TextOverflow.fade– fades out the text.
TextOverflow.visible– allows the text to overflow its bounds.
You often combine overflow with maxLines to limit the number of lines.
Line Control: maxLines and softWrap
maxLines: Limits the number of lines. Use withoverflowto show an ellipsis when the limit is reached.softWrap: Iftrue, the text will wrap onto new lines when it reaches the edge. Iffalse, it will overflow horizontally (andmaxLinesmay be ignored). By default,softWrapistrue.
Using Text with Theme
Instead of hard‑coding styles, you can leverage the app's theme. Use Theme.of(context).textTheme to access predefined text styles like headlineMedium, titleLarge, bodyMedium, etc. This ensures consistency across the app.
Text Direction and Locale
You can control the text direction (e.g., for Arabic, Hebrew) using textDirection. The locale can be specified with locale to influence rendering of certain characters.
Key Takeaways
Textdisplays a string with a single style.
- Use
stylewithTextStyleto customize font, color, size, etc.
- Use
- Control alignment with
textAlign.
- Control alignment with
- Manage overflow with
overflowandmaxLines.
- Manage overflow with
- Use
softWrapto allow line breaks.
- Use
- Prefer theme‑based styles for consistency and adaptability.
- Always handle text overflow to avoid layout errors.