Skip to content
DeveloperMemos

Underlining Text in Flutter

Flutter, Mobile Development, UI Design1 min read

In Flutter, underlining text is a common requirement for UI design. Unlike some other frameworks, underlining text in Flutter is not done through a fontStyle property but through text decoration. This article will guide you on how to underline text in Flutter using TextStyle and TextSpan.

Using TextStyle for Underlining

For simple text underlining, the TextStyle property of the Text widget can be used.

Example:

1import 'package:flutter/material.dart';
2
3void main() {
4 runApp(MyApp());
5}
6
7class MyApp extends StatelessWidget {
8 @override
9 Widget build(BuildContext context) {
10 return MaterialApp(
11 home: Scaffold(
12 body: Center(
13 child: Text(
14 'Hello world',
15 style: TextStyle(
16 decoration: TextDecoration.underline,
17 ),
18 ),
19 ),
20 ),
21 );
22 }
23}

Underlining Part of the Text

If you need to underline only part of the text, use Text.rich() or a RichText widget with TextSpan.

Example:

1import 'package:flutter/material.dart';
2
3void main() {
4 runApp(MyApp());
5}
6
7class MyApp extends StatelessWidget {
8 @override
9 Widget build(BuildContext context) {
10 return MaterialApp(
11 home: Scaffold(
12 body: Center(
13 child: Text.rich(
14 TextSpan(
15 text: 'Hello ',
16 style: TextStyle(fontSize: 20),
17 children: <TextSpan>[
18 TextSpan(
19 text: 'world',
20 style: TextStyle(
21 decoration: TextDecoration.underline,
22 ),
23 ),
24 ],
25 ),
26 ),
27 ),
28 ),
29 );
30 }
31}

Customizing the Underline Style

Flutter allows you to customize the underline style. You can use decorationStyle property to apply different styles like dashed, dotted, double, or wavy.

Example of Dashed Underline:

1Text(
2 'Dashed Underline',
3 style: TextStyle(
4 decoration: TextDecoration.underline,
5 decorationStyle: TextDecorationStyle.dashed,
6 ),
7)

Conclusion

Underlining text in Flutter is straightforward and customizable. By using the TextStyle property for simple underlining or TextSpan for more complex cases, you can easily apply underlines to your text. Additionally, the decorationStyle property offers further customization to match your UI design needs.