Search code examples
androidflutterfonts

In my Flutter Project, I want to customize the font of a text, but it doesn't work


This is the pubspec.yaml. I defined the fonts that I am going to use and I copied the font file to fonts directory of my android project.

name: your_flutter_app
description: A new Flutter project
environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  math_expressions: ^2.0.0  # Add this line to include the math_expressions package
flutter:
 fonts:
   - family: My-font
     fonts:
       - asset: fonts/Yarndings20Charted-regular.ttf

And this is my main.dart:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
  home: Scaffold (
    appBar: AppBar(
      title: Text('my First App'),
      centerTitle: true,
      backgroundColor: Colors.amber.shade100,
    ),
    body: Center(
      child: Text(
          'I am  Haroon',
        style: TextStyle(
            fontSize: 20,
            color: Colors.green,
            fontFamily: 'My-font',
        ),
      ),
    ),
    floatingActionButton: FloatingActionButton(
      child: Text('click'),
      onPressed: () {
        //Something Here;
      },
      backgroundColor: Colors.green,
    ),
  ),
));


I used pub.get and update dependencies. But none worked!


Solution

  • There might some cases:

    1. Ensure that the font file (Yarndings20Charted-regular.ttf) is located in the correct directory within your Flutter project.
    2. Double-check that the family name specified in your pubspec.yaml matches the actual family name embedded in the font file.
    3. Sometimes, changes to the pubspec.yaml file may not take effect immediately. Try hot-reloading your app by pressing r in the terminal or restarting your app to see if the font is loaded correctly.
    4. Sometimes, cached assets may cause issues with font loading. You can try clearing the Flutter build cache by running flutter clean in your terminal and then rebuilding your app.