Search code examples
flutterflutter-dependenciespubspec

Using a custom icon font in a Flutter package displays Question marks instead of custom icons


I have an application composed of a number of different Dart and Flutter packages. This has proven useful in that I've been able to move things like fonts, colours and Widgets into an independent style guide package which we can then use across all of our other applications.

Using custom fonts in a package works slightly differently in Flutter as we need to add the assets directory as a child of lib rather than a sibling:

Adding assets to a package

…and then register these assets in pubspec.yaml like so:

assets:
 - packages/receipt_widget/assets/fonts/my_font.ttf
 // other asset declarations

This, for custom fonts and icons (png, jpg etc) works completely fine. My issue is that the same approach does not work for custom icon fonts.

Steps:

  • Generate custom icon font using IcoMoon or Flutter Icon
  • Place the generated font into the assets/fonts directory as demonstrated above
  • Place the generated dart file into the lib folder
  • Reference the custom icon in code and place into an Icon widget like so:
Icon(MyFontIcon.ic_heart);

For safety I then run flutter clean and uninstall the app from the device/ emulator before deploying a clean build. I'm then left with a question mark rather than the referenced icon.

NB. the very same icons work correctly when used in a Flutter application directly rather than in a package.


Solution

  • To use your Flutter Icon font from a custom package, you can follow these steps: (I repeated some of your steps already, for others who will find this issue)

    create a flutter icon font

    You can use flutter icon for that https://www.fluttericon.com

    Put the file into your package

    Make sure to copy the .ttf file into of the /lib folder. NOT just assets, as you would do in your root project.

    Example path:

    /packages/my_awesome_fontpackage/lib/assets/MyIconFont.ttf
    

    (see https://zubairehman.medium.com/how-to-use-custom-fonts-images-in-flutter-package-c2d9d4bfd47a )

    Add the font to your project

    Now open your package's pubspec.yaml file and add the font as an asset with package path:

    flutter:
      fonts:
      - family:  MyIconFont
        fonts:
          - asset: packages/my_awesome_fontpackage/assets/MyIconFont.ttf
    

    (you might have to restart your app and bundling completely for the font to be loaded correctly and maybe run flutter clean just to be sure)

    Now add package declaration to font dart file

    Go into the my_icon_font.dart file and change the constant _kFontPkg there to your package name.

    
    class MyIconFont {
      MyIconFont._();
    
      static const _kFontFam = 'MyIconFont';
      static const String? _kFontPkg = 'my_awesome_fontpackage';
    
      static const IconData bell = ...
      ....
    }