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 {
  final String normalizedFamily = removeQuotationMark(fontFamily).trim();
  if (normalizedFamily.isEmpty) return;

  final FontStyle targetStyle = renderStyle.fontStyle;

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

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

  if (descriptor == null) {
    return;
  }

  final String descriptorKey = _getFontKey(descriptor.fontFamily, descriptor.fontWeight, descriptor.fontStyle);
  if (_loadedFonts.contains(descriptorKey)) return;

  // Start loading and track the future
  final existingLoad = _loadingFonts[descriptorKey];
  if (existingLoad != null) return existingLoad;

  final loadFuture = _loadFont(descriptor);
  _loadingFonts[descriptorKey] = loadFuture;

  try {
    final bool loaded = await loadFuture;
    if (loaded) {
      descriptor.isLoaded = true;
      _loadedFonts.add(descriptorKey);
    }
  } finally {
    // Remove from loading map when done
    _loadingFonts.remove(descriptorKey);
    renderStyle.markNeedsLayout();
  }
}