loadFontsIfNecessary function

Future<void> loadFontsIfNecessary(
  1. String fontFamily,
  2. Map<WebFontsVariant, WebFontsFile> fonts
)

Loads a font into the FontLoader

If a font with the fontName has already been loaded into memory, then this method does nothing as there is no need to load it a second time.

Otherwise, this method will first check to see if the font is available as an asset, then on the device file system. If it isn't, it is fetched via the fontUrl and stored on device. In all cases, the font is loaded into the FontLoader.

Implementation

Future<void> loadFontsIfNecessary(
    String fontFamily, Map<WebFontsVariant, WebFontsFile> fonts) async {
  // If this font has already already loaded or is loading, then there is no
  // need to attempt to load it again, unless the attempted load results in an
  // error.
  if (_loadedFonts.contains(fontFamily)) {
    return;
  } else {
    _loadedFonts.add(fontFamily);
  }

  final fontLoader = FontLoader(fontFamily);

  await Future.wait(fonts.keys.map((fontVariant) {
    final fontFile = fonts[fontVariant];

    if (fontFile == null) {
      return Future.value();
    }

    return (() async {
      final byteData = await _loadFontByteData(
        WebFontsDescriptor(
            familyWithVariant: WebFontsFamilyWithVariant(
                family: fontFamily, fontsVariant: fontVariant),
            file: fontFile),
      );

      if (byteData == null) {
        return;
      }

      fontLoader.addFont(Future.value(byteData));
    })();
  }));

  await fontLoader.load();
}