This tutorial shows you how to create strikethrough text in Flutter.
Sometimes, you may want to display a text that's decorated with a strikethrough to indicate that the information is not valid. The most common usage is for displaying the original price of discounted items. If you're using Flutter, displaying such a text is very simple. Below I'm going to show you several ways to do it.
Using Text
Widget
Using a Text
widget is the simplest way for displaying text in Flutter. The widget allows you to pass an argument named style
whose type is TextStyle
. The TextStyle
class itself can be used to define the style of the text, such as the size, font, and decoration. For adding a strikethrough, you can create a TextStyle
whose decoration
value is TextDecoration.lineThrough
.
Text(
'Woolha.com',
style: TextStyle(
fontSize: 24.0,
decoration: TextDecoration.lineThrough,
),
)
Output:
Using RichText
& TextSpan
Widgets
If you set a decoration to a Text
widget like the example above, it will be applied on all characters. In many cases, usually only a part of the text that's decorated with the strikethrough. The solution is to use a RichText
widget. Using the RichText
widget, you can define several TextSpan
widgets with each of them having different styles. Defining a TextStyle
of a TextSpan
is the same as on a Text
widget, which can be done by passing it as the style
argument.
RichText(
text: const TextSpan(
children: <TextSpan>[
TextSpan(
text: 'Price: ',
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
TextSpan(
text: '\$100',
style: TextStyle(
color: Colors.grey,
fontSize: 20.0,
decoration: TextDecoration.lineThrough,
),
),
TextSpan(
text: ' \$50',
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
],
),
)
Output:
Combine with Other Decorations
Sometimes, you may want to add other decorations to the text in addition to the strikethrough. For example, you want to display a text with both underscore and strikethrough. In Flutter, multiple decorations can be combined by using the TextDecoration.combine
method, which allows you to pass a list of TextDecoration
values.
Text(
'Woolha.com',
style: TextStyle(
fontSize: 24.0,
decoration: TextDecoration.combine([
TextDecoration.underline,
TextDecoration.lineThrough,
]),
),
)
Output:
Summary
To add a strikethrough decoration to a text in Flutter, you can create a TextStyle
which uses TextDecoration.lineThrough
. The style can be applied to any widget that accepts a TextStyle
argument, such as Text
or TextSpan
. To combine the strikethrough with other decorations, use the TextDecoration.combine
method.