loadCachedFamily static method

Future<Iterable<FileInfo>> loadCachedFamily(
  1. List<String> urls, {
  2. required String fontFamily,
  3. @visibleForTesting FontLoader? fontLoader,
})

Fetches the given urls from cache and loads them into the engine to be used.

urls should be a series of related font assets, each of which defines how to render a specific FontWeight and FontStyle within the family.

Call canLoadFont before calling this method to make sure the font is available in cache.

  • REQUIRED The urls property is used to specify the urls for the required family. It should be a list of valid http/https urls which point to font files. Every url in urls should be loaded into cache by calling cacheFont for each.

  • REQUIRED The fontFamily property is used to specify the name of the font family which is to be used as TextStyle.fontFamily.

Implementation

static Future<Iterable<FileInfo>> loadCachedFamily(
  List<String> urls, {
  required String fontFamily,
  @visibleForTesting FontLoader? fontLoader,
}) async {
  fontLoader ??= FontLoader(fontFamily);
  final List<FileInfo> fonts = [];

  WidgetsFlutterBinding.ensureInitialized();

  for (final String url in urls) {
    final String cacheKey = Utils.sanitizeUrl(url);

    final FileInfo? font =
        await DynamicCachedFontsCacheManager.getCacheManager(cacheKey)
            .getFileFromCache(cacheKey);

    if (font == null)
      throw StateError('Font should already be cached to be loaded');

    fonts.add(font);

    final Uint8List fontBytes = await font.file.readAsBytes();

    final ByteData cachedFontBytes = ByteData.view(fontBytes.buffer);

    fontLoader.addFont(Future<ByteData>.value(cachedFontBytes));
  }

  await fontLoader.load();

  devLog(<String>['Font has been loaded!']);

  return fonts;
}