loadCachedFont static method

Future<FileInfo> loadCachedFont(
  1. String url, {
  2. required String fontFamily,
  3. @visibleForTesting FontLoader? fontLoader,
})

Fetches the given url from cache and loads it as an asset.

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

  • REQUIRED The url property is used to specify the url for the required font. It should be a valid http/https url which points to a font file. The url should match the url passed to cacheFont.

  • 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<FileInfo> loadCachedFont(
  String url, {
  required String fontFamily,
  @visibleForTesting FontLoader? fontLoader,
}) async {
  fontLoader ??= FontLoader(fontFamily);

  WidgetsFlutterBinding.ensureInitialized();

  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');

  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!',
    'This font file is valid till - ${font.validTill}',
    'File stat - ${font.file.statSync()}'
  ]);

  return font;
}