Support multiple asset types

This commit is contained in:
Pyrex 2023-09-19 15:33:45 -07:00
parent 01d39ec58d
commit 49027d74fe

View File

@ -3,26 +3,39 @@ import 'dart:ui' as ui;
import 'package:flutter/services.dart';
class Assets {
final Map<String, ui.Image> _loaded = {};
final Set<String> _waiting = {};
Future<ui.Image> _getImageAsync(String name) async {
final _Table<ui.Image> _images = _Table((name) async {
final assetImageByteData = await rootBundle.load(name);
final codec =
await ui.instantiateImageCodec(assetImageByteData.buffer.asUint8List());
final image = (await codec.getNextFrame()).image;
_loaded[name] = image;
return image;
}
});
ui.Image? getImageIfAvailable(String name) {
return _images.getIfAvailable(name);
}
}
class _Table<T> {
final Map<String, T> _loaded = {};
final Set<String> _waiting = {};
final Future<T> Function(String) _getAsync;
_Table(this._getAsync);
T? getIfAvailable(String name) {
if (!_waiting.contains(name)) {
_waiting.add(name);
_getImageAsync(name);
_spawnGetAsync(name);
}
return _loaded[name];
}
Future<void> _spawnGetAsync(String name) async {
final asset = await _getAsync(name);
_loaded[name] = asset;
}
}
final assets = Assets();