imageFromAsset function Assets and loading

Future<Image> imageFromAsset(
  1. String assetPath, {
  2. AssetBundle? bundle,
})

Loads and decodes an image from the asset bundle at assetPath.

Uses dart:ui's built-in image codecs (PNG, JPEG, etc.). Throws if the asset is not present in the bundle or cannot be decoded.

Implementation

Future<ui.Image> imageFromAsset(String assetPath, {AssetBundle? bundle}) async {
  // Load resource from the asset bundle. Throws exception if the asset couldn't
  // be found in the bundle.
  final buffer = await (bundle ?? rootBundle).loadBuffer(assetPath);

  // Decode the image.
  final codec = await ui.instantiateImageCodecFromBuffer(buffer);
  final frame = await codec.getNextFrame();
  return frame.image;
}