Have you been looking for ways to understand test styling and custom fonts in Flutter? Here’s an easy step by step guide on how you can style your text in Flutter.
There are different ways regarding the appearance of Text: TextStyle and Custom Fonts. We’ll deal with these in this post, as do well to read to the end, as You’ll better understand text theming, and ways of which you can style your text in Flutter to birth a beautiful UI. Firstly, let’s talk about;
TextStyle
Text widgets have a style property which takes a TextStyle()
object. See an example in the image below;
You’ll simply set the style property to an instance of a TextStyle widget and set properties. The TextStyle
in Flutter supports about 20 properties. Here are the most useful:
color
– Any of the valid 16+ million colorsdecoration
– TextDecoration.underline, overline, strikethrough, nonefontSize
– A double. The number of pixels tall to make the characters. Default size 14.0 pixelsfontStyle
– FontStyle.italic or normalfontWeight
– FontWeight.w100-w900. Or bold (which is w700) or normal (which is w400)fontFamily
– A string
The fontFamily
is a bigger topic. There are some fonts that are built-in like Courier, Times New Roman, serif, and a bunch more. How many more? It depends on the type of device on which the app is running. Since we don’t have control over the users’ devices, the best practice is for you to stick to the default font family unless you install and use a custom font. Let’s talk about how to do that.
Custom Fonts
Certain designers call for custom fonts when they design scenes. It turns out with Flutter, using custom fonts is easy to implement, and they work cross-platform. It involves three steps:
- Download the custom font files which are in ttf, woff, or woff2 format. These are customarily stored in a root-level folder called fonts, but the name is up to you.
You may be asking, Where can I get amazing fonts? You can find some excellent and free fonts at https://fonts.google.com. Search through them by type, see samples, and download them easily. Now, How do you add Custom Fonts in Flutter.
- Add the font files to the pubspec.yaml file under flutter/fonts so that the compiler is notified to bundle them in the installation file.
flutter: fonts: - family: MrDafoe fonts: - asset: fonts/MrDafoe-Regular.ttf - family: NanumBrushScript fonts: - asset: fonts/NanumBrushScript-Regular.ttf
- Use the case-insensitive font name in the fontFamily property of the TextStyle widget as it helps understand your code better. Here’s how you can apply the font in your text
Text(loremIpsums[0]), // Unstyled Text(loremIpsums[1], // Some, like Courier may be built-in style: TextStyle(fontFamily: 'Courier'),), Text(loremIpsums[2], style: TextStyle(fontFamily: 'NanumBrushScript'),), Text(loremIpsums[3], style: TextStyle(fontFamily: 'MrDafoe'),),