Sub topic 2
Styling text with TextStyle
This chapter assumes you know basic Dart syntax, Flutter widgets, StatelessWidget, the build method, and pubspec.yaml. It also assumes you can run a Flutter project.
A TextStyle describes how Flutter paints text. It can control:
fontSize: the size in logical pixels.fontWeight: the thickness, such asFontWeight.normalorFontWeight.bold.color: the text color.fontStyle: normal or italic text.letterSpacing: extra space between characters.wordSpacing: extra space between words.height: the line height multiplier.decoration: effects such as an underline.
The Text widget accepts a style through its style parameter:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: StyledTextExample()));
}
class StyledTextExample extends StatelessWidget {
const StyledTextExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('TextStyle')),
body: const Center(
child: Text(
'Readable Flutter text',
style: TextStyle(
color: Colors.indigo,
fontSize: 24,
fontWeight: FontWeight.w700,
height: 1.3,
letterSpacing: 0.4,
),
),
),
);
}
}TextStyle is immutable. This means that after creating one, you do not change its fields. Instead, create a new style or use copyWith to derive one from an existing style.
Combining styles safely
A direct style replaces the style inherited from a parent widget or theme. If you want to change only one property, use copyWith:
Text(
'Warning',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: Colors.red,
fontWeight: FontWeight.bold,
),
)This keeps the theme's font family and size while changing the color and weight. The nullable ? is needed because some theme text styles can be absent.
Use const TextStyle when every value is known at compile time. Const objects can be reused without being recreated during builds.
How style properties affect layout
Text style affects more than appearance. A larger font, wider letter spacing, or greater line height changes the space that the text needs. A fixed-width parent may therefore cause the text to wrap or overflow.
Common mistakes include:
- Using
fontWeight: FontWeight.boldeverywhere instead of establishing a clear hierarchy. - Setting
heighttoo low, which makes lines hard to read. - Replacing a theme style when you intended to change only its color.
- Assuming a style prevents overflow. Layout constraints still control whether text fits.
Exercise
Exercise
Starting with a theme style, how would you make a heading red and bold without replacing its font size?
Show answer
Use Theme.of(context).textTheme.headlineSmall?.copyWith(color: Colors.red, fontWeight: FontWeight.bold).