ensureFontLoaded static method

Future<void> ensureFontLoaded(
  1. String fontFamily,
  2. FontWeight fontWeight,
  3. CSSRenderStyle renderStyle
)

Implementation

static Future<void> ensureFontLoaded(String fontFamily, FontWeight fontWeight, CSSRenderStyle renderStyle) async {
  String fontKey = _getFontKey(fontFamily, fontWeight);

  // Already loaded
  if (_loadedFonts.contains(fontKey)) {
    return;
  }

  // Already loading - wait for existing load to complete
  if (_loadingFonts.containsKey(fontKey)) {
    return _loadingFonts[fontKey]!;
  }

  // Find matching font descriptor
  List<FontFaceDescriptor>? descriptors = _fontFaceRegistry[fontFamily];
  if (descriptors == null || descriptors.isEmpty) {
    return;
  }

  // Find exact weight match or closest fallback
  FontFaceDescriptor? descriptor = _findBestMatchingDescriptor(descriptors, fontWeight);

  if (descriptor == null || descriptor.isLoaded) {
    return;
  }

  // Mark as loaded immediately to prevent race conditions
  descriptor.isLoaded = true;
  _loadedFonts.add(fontKey);

  // Also mark the actual font weight as loaded to prevent duplicate loads
  // when the exact weight is requested later
  String actualFontKey = _getFontKey(descriptor.fontFamily, descriptor.fontWeight);
  _loadedFonts.add(actualFontKey);

  // Start loading and track the future
  final loadFuture = _loadFont(descriptor);
  _loadingFonts[fontKey] = loadFuture;
  _loadingFonts[actualFontKey] = loadFuture;

  try {
    await loadFuture;
  } finally {
    // Remove from loading map when done
    _loadingFonts.remove(fontKey);
    if (actualFontKey != fontKey) {
      _loadingFonts.remove(actualFontKey);
    }
    renderStyle.markNeedsLayout();
  }
}