Nicolas Degen
Nicolas Degen

Reputation: 1846

Set Fallback Font globally in Flutter

In Flutter, I do set the fallback font on every single text widget like that:

Text('Sample, style:'TextStyle(fontSize: 22, fontFamilyFallback: ['AppleColorEmoji']))

I can set the text font in ThemeData as fontFamily , but not the fallback font.

Is there any alternative?

Upvotes: 4

Views: 5218

Answers (1)

Bach
Bach

Reputation: 3326

The best way to define a general theme for a Flutter app is through the theme attribute of MaterialApp. You can do it like this:

MaterialApp(
  title: 'Sample App',
  theme: ThemeData(
    // Define the default brightness and colors.
    brightness: Brightness.dark,
    primaryColor: Colors.lightBlue[800],
    accentColor: Colors.cyan[600],

    // Define the default font family.
    fontFamily: 'Georgia',

    // Define the default TextTheme. Use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: const TextTheme(
      bodyText2: TextStyle(fontSize: 22, fontFamilyFallback: ['AppleColorEmoji']), // Default style for Material Text
      subtitle1: TextStyle(fontSize: 24, fontFamilyFallback: ['AppleColorEmoji']), // Define your own style of subtitle
    ),
  ),
  home: Scaffold(
      appBar: AppBar(title: Text('Sample title', style: Theme.of(context).textTheme.subtitle1)), // Use your default config like this
      body: Text('Sample content'), // Without style, it will use your bodyText2 config
  ),
);

Read more on Flutter's Theme here

Updated: To only set a fallback Font globally for your app, use the DefaultTextStyle at the root widget. For example:

Scaffold(
      body: DefaultTextStyle(
        style: TextStyle(fontFamilyFallback: ['AppleColorEmoji']),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'The first text',
              ),
            ],
          ),
        ),
      ),
    )

You can read more on the Text documentation here

The style argument is optional. When omitted, the text will use the style from the closest enclosing DefaultTextStyle.

Upvotes: 3

Related Questions