nearestVariantUrl method Null safety

String nearestVariantUrl(
  1. {required MediaAssetFormatVariant variant}
)

Looks up the specified format variant in the asset and returns the corresponding URL. If the URL is not found, it will return the next largest variant. If none are found, will return the asset's main URL. This method is designed to work with image assets that reside in Strapi's media library.

Implementation

String nearestVariantUrl({required MediaAssetFormatVariant variant}) {
  // if we do not have any format variants at all, return the default url
  if (formats.isEmpty) {
    return url;
  }

  // if the requested variant exists, return that one
  if (formats.containsKey(variant)) {
    return formats[variant]!.url;
  }

  // the requested variant doesn't exist, so find the next larger one
  var largerVariant = _largerVariantThan(variant);
  while (largerVariant != null) {
    if (formats.containsKey(largerVariant)) {
      return formats[largerVariant]!.url;
    }
    largerVariant = _largerVariantThan(largerVariant);
  }

  // no suitable variant was found, so use the default url
  return url;
}