— Flutter, Mobile Development, UI Design — 1 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
.
For simple text underlining, the TextStyle
property of the Text
widget can be used.
1import 'package:flutter/material.dart';2
3void main() {4 runApp(MyApp());5}6
7class MyApp extends StatelessWidget {8 @override9 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}
If you need to underline only part of the text, use Text.rich()
or a RichText
widget with TextSpan
.
1import 'package:flutter/material.dart';2
3void main() {4 runApp(MyApp());5}6
7class MyApp extends StatelessWidget {8 @override9 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}
Flutter allows you to customize the underline style. You can use decorationStyle
property to apply different styles like dashed, dotted, double, or wavy.
1Text(2 'Dashed Underline',3 style: TextStyle(4 decoration: TextDecoration.underline,5 decorationStyle: TextDecorationStyle.dashed,6 ),7)
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.