In Flutter, the Text widget is used to display a piece of text with a single style. It’s a fundamental widget for rendering text in your app. Here’s an explanation of the Text widget in Flutter
Text(
'Hello, Flutter!',
)
Key Properties
- data (String):
- The actual text content that you want to display.
- style (TextStyle):
- Defines the styling for the text, such as font size, color, and weight.
- textAlign (TextAlign):
- Specifies the alignment of the text within its container (left, center, right).
- maxLines (int):
- Sets the maximum number of lines for the text. If null, there is no limit.
- overflow (TextOverflow):
- Determines how overflowing text should be handled, whether it should be clipped, ellipsized, or displayed on multiple lines.
- textDirection (TextDirection):
- Specifies the directionality of the text, such as left-to-right or right-to-left.
Styling Text Widget in Flutter
Text(
'Styled Text',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline,
),
)
Multiline Text widget in Flutter
Text(
'This is a long piece of text that might span multiple lines.',
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
)
Dynamic Text widget in Flutter
String dynamicText = 'Dynamic Text';
Text(
dynamicText,
style: TextStyle(fontSize: 18.0),
)
Justify Text widget in Flutter
Text(
'This is a long piece of text that might span multiple lines.',
textAlign: TextAlign.justify,
maxLines: 2,
overflow: TextOverflow.ellipsis,
)
Text Color in Flutter
Text(
'Colored Text',
style: TextStyle(
color: Colors.blue, // Set the text color
),
)
Change Font Family of Text Widget in Flutter
Text(
'Custom Font Family',
style: TextStyle(
fontFamily: 'YourCustomFont', // Replace with the name of your custom font
),
)
Underline Text Widget in Flutter
Text(
'Underlined Text',
style: TextStyle(
decoration: TextDecoration.underline, // Add underline to the text
),
)
Flutter Text – Programmatically Change Font Size
class DynamicTextExample extends StatefulWidget {
@override
_DynamicTextExampleState createState() => _DynamicTextExampleState();
}
class _DynamicTextExampleState extends State<DynamicTextExample> {
double fontSize = 16.0;
void increaseFontSize() {
setState(() {
fontSize += 2.0; // Increase the font size by 2.0
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Dynamic Font Size',
style: TextStyle(fontSize: fontSize),
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: increaseFontSize,
child: Text('Increase Font Size'),
),
],
);
}
}