fromMemory static method

Future<AtlasFlutter> fromMemory(
  1. String atlasFileName,
  2. Future<Uint8List> loadFile(
    1. String name
    )
)

Loads an AtlasFlutter using a custom file loading function.

This is the most flexible loading method that allows loading atlas data and images from any source (memory, custom storage, network with caching, etc.).

Parameters:

  • atlasFileName: The path/name of the atlas file. This is passed to loadFile to load the atlas data.
  • loadFile: A function that takes a filename and returns the file data as Uint8List. This function will be called once for the atlas file, and once for each atlas page image. The image paths are relative to the atlas file's directory (as specified in the atlas file).

Example - Loading from memory:

final atlasData = Uint8List.fromList([...]); // Your atlas file data
final page1Data = Uint8List.fromList([...]); // Your first page image data
final page2Data = Uint8List.fromList([...]); // Your second page image data

final atlas = await AtlasFlutter.fromMemory(
  'character.atlas',
  (filename) async {
    if (filename == 'character.atlas') return atlasData;
    if (filename == 'character.png') return page1Data;
    if (filename == 'character2.png') return page2Data;
    throw Exception('Unknown file: $filename');
  },
);

Note: The loadFile function receives the full relative path for images (e.g., "directory/page.png" if the atlas file specifies that path).

Implementation

static Future<AtlasFlutter> fromMemory(String atlasFileName, Future<Uint8List> Function(String name) loadFile) async {
  // Load atlas data
  final atlasBytes = await loadFile(atlasFileName);
  final atlasData = convert.utf8.decode(atlasBytes);
  final atlas = loadAtlas(atlasData);

  // Load images for each atlas page
  final atlasDir = path.dirname(atlasFileName);
  final pages = <Image>[];
  final paints = <Map<BlendMode, Paint>>[];

  // Load images for each atlas page
  for (int i = 0; i < atlas.pages.length; i++) {
    final page = atlas.pages[i];
    if (page == null) continue;

    // Get the texture path from the atlas page
    final texturePath = page.texturePath;
    final imagePath = "$atlasDir/$texturePath";

    final imageData = await loadFile(imagePath);
    final codec = await instantiateImageCodec(imageData);
    final frameInfo = await codec.getNextFrame();
    final image = frameInfo.image;
    pages.add(image);

    // Create paints for each blend mode
    final pagePaints = <BlendMode, Paint>{};
    for (final blendMode in BlendMode.values) {
      pagePaints[blendMode] = Paint()
        ..shader = ImageShader(
          image,
          TileMode.clamp,
          TileMode.clamp,
          Matrix4.identity().storage,
          filterQuality: filterQuality,
        )
        ..isAntiAlias = true
        ..blendMode = blendMode.toFlutterBlendMode();
    }
    paints.add(pagePaints);
  }

  return AtlasFlutter._(atlas.nativePtr.cast(), pages, paints);
}