Flutter: Apply style as a Theme in a Text widget

Bhavik Makwana
Flutter Community
Published in
3 min readFeb 4, 2019

I am writing this article as a part of my weekly Flutter and Dart Tip. I know what you are thinking, a tip should not be as big as an article but today’s tip does deserve one small article. 😉

Yes, As the title suggests we are going to discuss “how to apply default Text Theme in your Text style”.

If you are an Android developer you may have used the android:textAppearance in your TextViews and used the @style/TextAppearance.AppCompat.Body1 and more.

The one who does not know about it, This is a style that allows you to style your Text in default Material guidelines style reference of Title, Body, Caption and many more.

So how you can implement this in Flutter’s Text widget?

It is easy as all things in Flutter are. 😃

You just need to give your style a TextThem using Theme.of(context).textTheme

Below is a sample code of it.

Text(
“Your Text”,
style: Theme.of(context).textTheme.title,
),

Here I have used the title.
You can use many more like…

Theme.of(context).textTheme.body1
Theme.of(context).textTheme.body2
Theme.of(context).textTheme.button
Theme.of(context).textTheme.caption
...
and Many more
...

Yeah...

You got it working but there is an issue. 😐

How you can customize this textTheme?? Like if you want a different color or any other fonts then what?

There is a solution for that too.

You just need to invoke the merge() function with your textTheme like below.

Theme.of(context)
.textTheme
.title
.merge(TextStyle(color: Colors.red)

Here merge function merges the already applied theme with the new TextStyle.

There are more functions like a merge().

  1. apply() : That creates a copy of text style replacing or altering the specified properties in it.
  2. copyWith() : It creates a copy of text style but with the given fields replaced with the new values.

That’s it for this week guys.

See you next week with new Tip, Till that Keep Fluttering.

You can check #1 Flutter + Dart Tips article if you missed it, and my Github repository for FlutterDartTips.

If you found this article helpful Click on 👏 as many time you can and help it to reach out to around the world.

--

--

Bhavik Makwana
Flutter Community

Flutter Enthusiast | Google Certified Associate Android Developer | Speaker for flutter | Android Dev | Flutter Dev