Home > Software engineering >  How to specify a monospace font in Flutter?
How to specify a monospace font in Flutter?

Time:01-31

I want to specify a monospace font in a Text widget:

Text("I would like this to be monospace.")

How can I do that? I don't care about the actual font so long as it is monospace because this is for a developer-only screen.

CodePudding user response:

As per the official docs, you should:

  1. Import the font files.
  2. Declare the font in the pubspec.
  3. Set a font as the default.
  4. Use a font in a specific widget.

Now I will put these steps from the document here, and you can read the entire document if you want more details:

Step 1:

After you have your fonts ready (ttf for example), you add them to your project directory under the assets folder, for example (from the link above):

awesome_app/
  fonts/
    Raleway-Regular.ttf
    Raleway-Italic.ttf
    RobotoMono-Regular.ttf
    RobotoMono-Bold.ttf

Step 2:

Declare the font in pubspec.yaml, example:

flutter:
  fonts:
    - family: Raleway
      fonts:
        - asset: fonts/Raleway-Regular.ttf
        - asset: fonts/Raleway-Italic.ttf
          style: italic
    - family: RobotoMono
      fonts:
        - asset: fonts/RobotoMono-Regular.ttf
        - asset: fonts/RobotoMono-Bold.ttf
          weight: 700

Step 3:

You have two options for how to apply fonts to text: as the default font or only within specific widgets.

In your case, you want to use the font in a specific widget, so you do:

child: Text(
  'Roboto Mono sample',
  style: TextStyle(fontFamily: 'RobotoMono'),
),
  • Related