The Text widget in Flutter is used to display text on the screen. It's one of the most fundamental widgets and supports a wide range of customizations to style, align, and manage text. Here’s a detailed overview:
Basic Syntax
Key Properties
data
:- The text string to display.
- Example:
'Hello, World!'
.
style
:- Defines the appearance of the text.
- Uses the
TextStyle
class for customization.
Example:
textAlign
:- Aligns the text horizontally.
- Values:
TextAlign.left
,TextAlign.right
,TextAlign.center
,TextAlign.justify
, etc. - Example:
maxLines
:- Limits the number of lines to display.
- Example:
overflow
:- Controls how the text behaves when it overflows the available space.
- Options:
TextOverflow.clip
(trims text at the boundary)TextOverflow.ellipsis
(adds "...")TextOverflow.fade
(fades out the text)
- Example:
softWrap
:- Determines whether text should wrap when it exceeds its width.
- Example:
textScaleFactor
:- Scales the text size.
- Default is
1.0
. - Example:
strutStyle
:- Defines vertical layout constraints like height and baseline alignment.
- Used for fine-grained control over text spacing.
TextStyle Class
The TextStyle
object is used to style the text. Common properties include:
fontSize
: Sets the font size.color
: Sets the text color.fontWeight
: Controls the thickness (e.g.,FontWeight.bold
).fontStyle
: Makes the text italic (FontStyle.italic
).letterSpacing
: Adjusts spacing between letters.wordSpacing
: Adjusts spacing between words.decoration
: Adds decoration (e.g., underline, strike-through).
Advanced Features
Rich Text: If you need different styles in the same text block, use the
RichText
widget withTextSpan
.Example:
Localization: Use the
Text
widget with internationalization (i18n) support for multi-language apps using Flutter'sintl
package.
Examples
Centered Text:
Limited Lines with Ellipsis:
Multi-line Text:
Best Practices
- Use
Text
for simple, single-style text content. - Use
RichText
orTextSpan
for multi-style or dynamic text. - Leverage
maxLines
andoverflow
to handle large content gracefully.
Comments
Post a Comment