loadFont function

Future<void> loadFont(
  1. String family,
  2. List<String> fontPaths
)

Loads a fontFamily consisting of multiple font files.

debugDefaultTargetPlatformOverride = TargetPlatform.windows;
await loadFont('Comic Sans', [
  r'C:\Windows\Fonts\comic.ttf', // Regular
  r'C:\Windows\Fonts\comicbd.ttf', // Bold
  r'C:\Windows\Fonts\comici.ttf', // Italic
]);

tester.pumpWidget(
  MaterialApp(
    home: Center(
      child: Text(
        'Loaded custom Font',
        style: TextStyle(
          fontFamily: 'Comic Sans',
        ),
      ),
    ),
  ),
);

Flutter support the following formats: .ttf, .otf, .ttc

Calling loadFont multiple times with the same family will overwrites the previous

The family is optional: '' will extract the family name from the font file.

Implementation

Future<void> loadFont(String family, List<String> fontPaths) async {
  if (kIsWeb) {
    // ignore: avoid_print
    print('⚠️ - loadFont is not supported on the web!');
    return;
  }

  if (fontPaths.isEmpty) {
    return;
  }

  await TestAsyncUtils.guard<void>(() async {
    final fontLoader = FontLoader(family);
    for (final path in fontPaths) {
      try {
        final file = File(path);
        if (file.existsSync()) {
          final Uint8List bytes = file.readAsBytesSync();
          fontLoader.addFont(Future.value(bytes.buffer.asByteData()));
        } else {
          final data = rootBundle.load(path);
          fontLoader.addFont(Future.value(data));
        }
      } catch (e, stack) {
        debugPrint("Could not load font $path\n$e\n$stack");
      }
    }
    // the fontLoader is unusable after calling load().
    // No need to cache or return it.
    await fontLoader.load();
  });
}