Ora

How do you make a custom text style in Flutter?

Published in Flutter Typography Styling 6 mins read

Creating a custom text style in Flutter primarily involves using the TextStyle class, which offers a wide array of properties to control the appearance of your text, from font family and size to color and spacing. For truly unique designs, incorporating custom fonts is also a common and straightforward process.

Understanding TextStyle in Flutter

The TextStyle class is the foundation for styling text in Flutter. You can apply it directly to a Text widget or manage styles globally using ThemeData. A TextStyle object allows you to define various attributes that control how your text is rendered.

Key Properties of TextStyle

Property Description Example Value
color The color of the text. Colors.blue
fontSize The size of the text in logical pixels. 18.0
fontWeight The thickness of the glyphs. FontWeight.bold
fontStyle Whether the text is italic or normal. FontStyle.italic
letterSpacing The amount of space between letters. 1.5
wordSpacing The amount of space between words. 2.0
height The height of the text as a multiple of the font size. 1.5
fontFamily The name of the font family to use. 'Roboto', 'MyCustomFont'
decoration A line to draw above, below, or through the text. TextDecoration.underline
decorationColor The color of the decoration. Colors.red
decorationStyle The style of the decoration line. TextDecorationStyle.dotted
shadows A list of shadows to paint behind the text. [Shadow(...)]
backgroundColor The color to paint behind the text. Colors.yellow

Incorporating Custom Fonts for Unique Styles

While TextStyle offers many properties, using a custom font can truly differentiate your app's typography. Flutter makes it straightforward to integrate external font files.

To use a custom font, follow these steps:

  1. Obtain Your Font Files

    Download your desired font files (e.g., .ttf, .otf) from reputable sources like Google Fonts. Ensure you have all the necessary weights and styles (e.g., regular, bold, italic).

  2. Create an Asset Directory

    In the root of your Flutter project, create a new directory, for example, assets/fonts. This is where your font files will reside. While you can name it anything, assets/fonts is a common convention.

  3. Add Font Files to the Directory

    Copy your desired font files (e.g., my_custom_font_regular.ttf, my_custom_font_bold.ttf) into this new assets/fonts directory. For instance, if you have a font named "OpenSans" with regular and bold variants, you might place OpenSans-Regular.ttf and OpenSans-Bold.ttf here.

  4. Declare Fonts in pubspec.yaml

    You must update your pubspec.yaml file to inform Flutter about your custom fonts. Under the flutter: section, add a fonts: entry. Each font family requires a family name and a list of asset paths for its variations, optionally specifying weight and style.

    flutter:
      uses-material-design: true
    
      # To add assets to your application, add an assets section, like this:
      assets:
        - assets/images/ # Example of other assets
    
      # To add custom fonts to your application, add a fonts section here,
      # in this "flutter" section. Each entry in this list should have a
      # "family" key with the font family name, and a "fonts" key with a
      # list giving the asset and other descriptors for the font.
      fonts:
        - family: CustomOpenSans # This is the name you'll use in TextStyle
          fonts:
            - asset: assets/fonts/OpenSans-Regular.ttf
            - asset: assets/fonts/OpenSans-Italic.ttf
              style: italic
            - asset: assets/fonts/OpenSans-Bold.ttf
              weight: 700 # Corresponds to FontWeight.bold
        - family: AnotherFontExample
          fonts:
            - asset: assets/fonts/AnotherFont-Regular.ttf

    After modifying pubspec.yaml, save the file and run flutter pub get in your terminal to ensure the changes are applied and assets are included in your project.

  5. Apply the Custom Font in TextStyle

    Once declared, you can use your custom font by specifying its family name in the fontFamily property of a TextStyle object.

    Text(
      'Hello, Custom Font!',
      style: TextStyle(
        fontFamily: 'CustomOpenSans', // Use the family name defined in pubspec.yaml
        fontSize: 24,
        fontWeight: FontWeight.w700, // Matches the weight 700 defined
        color: Colors.deepPurple,
      ),
    ),

Applying Custom Text Styles

There are several ways to apply custom text styles in Flutter, depending on the scope of your styling needs:

1. Direct Application to a Text Widget

This is the most straightforward method for styling individual Text widgets.

Text(
  'Welcome to my App!',
  style: TextStyle(
    color: Colors.blueAccent,
    fontSize: 20.0,
    fontWeight: FontWeight.bold,
    letterSpacing: 1.2,
    decoration: TextDecoration.underline,
    decorationColor: Colors.blueAccent,
    decorationStyle: TextDecorationStyle.solid,
  ),
),

2. Using ThemeData for App-Wide Consistency

For consistent styling across your entire application, you can define TextTheme within your ThemeData. This allows you to set default styles for various text types (e.g., headlines, body text) which can then be easily accessed throughout your app using Theme.of(context).textTheme.

MaterialApp(
  title: 'Custom Styles Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
    textTheme: const TextTheme(
      headlineLarge: TextStyle(
        fontFamily: 'CustomOpenSans',
        fontSize: 32.0,
        fontWeight: FontWeight.bold,
        color: Colors.deepPurple,
      ),
      bodyLarge: TextStyle(
        fontFamily: 'CustomOpenSans',
        fontSize: 16.0,
        color: Colors.black87,
      ),
      // ... define other text styles
    ),
  ),
  home: const MyHomePage(),
);

// In your widget:
Text(
  'This is a headline!',
  style: Theme.of(context).textTheme.headlineLarge,
);

You can also apply a default font family to your entire theme:

MaterialApp(
  theme: ThemeData(
    fontFamily: 'CustomOpenSans', // Sets the default font for the whole app
    // ... other theme properties
  ),
  // ...
);

3. Using DefaultTextStyle for Subtree Overrides

If you need to apply a consistent style to a specific part of your widget tree without affecting the entire app, DefaultTextStyle is useful. All Text widgets within its subtree will inherit this style unless explicitly overridden.

DefaultTextStyle(
  style: const TextStyle(
    color: Colors.green,
    fontSize: 18.0,
    fontStyle: FontStyle.italic,
  ),
  child: Column(
    children: const <Widget>[
      Text('This text is green and italic.'),
      Text('So is this one.'),
      Text(
        'But this one is red!',
        style: TextStyle(color: Colors.red), // Overrides the default
      ),
    ],
  ),
),

Best Practices and Tips

  • Consistency: Define a typographic scale in your ThemeData to maintain a consistent look and feel across your application.
  • Modularity: For complex or frequently used custom styles, consider creating extension methods or dedicated const variables to avoid repetition.
  • Performance: While Flutter handles fonts efficiently, be mindful of including too many different custom font files, as this can increase your app's bundle size.
  • Accessibility: Ensure your text styles provide sufficient contrast and legible font sizes for all users. The TextScaler widget can also assist with text scaling based on system settings.
  • Responsiveness: Use MediaQuery.of(context).textScaler.scale(fontSize) to scale font sizes dynamically based on user preferences.

By mastering the TextStyle class and effectively integrating custom fonts, you can achieve highly customized and visually appealing typography in your Flutter applications.