Support multiple asset types
This commit is contained in:
parent
01d39ec58d
commit
49027d74fe
@ -3,26 +3,39 @@ import 'dart:ui' as ui;
|
|||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
class Assets {
|
class Assets {
|
||||||
final Map<String, ui.Image> _loaded = {};
|
final _Table<ui.Image> _images = _Table((name) async {
|
||||||
final Set<String> _waiting = {};
|
|
||||||
|
|
||||||
Future<ui.Image> _getImageAsync(String name) async {
|
|
||||||
final assetImageByteData = await rootBundle.load(name);
|
final assetImageByteData = await rootBundle.load(name);
|
||||||
final codec =
|
final codec =
|
||||||
await ui.instantiateImageCodec(assetImageByteData.buffer.asUint8List());
|
await ui.instantiateImageCodec(assetImageByteData.buffer.asUint8List());
|
||||||
final image = (await codec.getNextFrame()).image;
|
final image = (await codec.getNextFrame()).image;
|
||||||
|
|
||||||
_loaded[name] = image;
|
|
||||||
return image;
|
return image;
|
||||||
}
|
});
|
||||||
|
|
||||||
ui.Image? getImageIfAvailable(String name) {
|
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)) {
|
if (!_waiting.contains(name)) {
|
||||||
_waiting.add(name);
|
_waiting.add(name);
|
||||||
_getImageAsync(name);
|
_spawnGetAsync(name);
|
||||||
}
|
}
|
||||||
return _loaded[name];
|
return _loaded[name];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _spawnGetAsync(String name) async {
|
||||||
|
final asset = await _getAsync(name);
|
||||||
|
_loaded[name] = asset;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final assets = Assets();
|
final assets = Assets();
|
||||||
|
Loading…
Reference in New Issue
Block a user