dartterm/lib/assets.dart

57 lines
1.3 KiB
Dart
Raw Normal View History

2023-09-06 03:11:15 +00:00
import 'dart:ui' as ui;
import 'package:dartterm/gen/generator.dart';
2023-09-06 03:11:15 +00:00
import 'package:flutter/services.dart';
class Assets {
2023-09-19 22:33:45 +00:00
final _Table<ui.Image> _images = _Table((name) async {
2023-09-06 03:11:15 +00:00
final assetImageByteData = await rootBundle.load(name);
final codec =
await ui.instantiateImageCodec(assetImageByteData.buffer.asUint8List());
final image = (await codec.getNextFrame()).image;
return image;
2023-09-19 22:33:45 +00:00
});
2023-09-06 03:11:15 +00:00
final _Table<Vaults> _vaults = _Table(Vaults.load);
2023-09-20 02:19:26 +00:00
2023-09-06 03:11:15 +00:00
ui.Image? getImageIfAvailable(String name) {
2023-09-19 22:33:45 +00:00
return _images.getIfAvailable(name);
}
2023-09-20 02:19:26 +00:00
Vaults? getVaultsIfAvailable(String name) {
return _vaults.getIfAvailable(name);
2023-09-20 02:19:26 +00:00
}
2023-09-19 22:33:45 +00:00
}
class _Table<T> {
final Map<String, T> _loaded = {};
final Set<String> _waiting = {};
2023-09-20 02:19:26 +00:00
final Future<T> Function(String) _loadAsync;
2023-09-19 22:33:45 +00:00
2023-09-20 02:19:26 +00:00
_Table(this._loadAsync);
2023-09-19 22:33:45 +00:00
T? getIfAvailable(String name) {
2023-09-06 03:11:15 +00:00
if (!_waiting.contains(name)) {
_waiting.add(name);
2023-09-20 02:19:26 +00:00
_spawnLoadAsync(name);
2023-09-06 03:11:15 +00:00
}
return _loaded[name];
}
2023-09-19 22:33:45 +00:00
2023-09-20 02:19:26 +00:00
Future<void> _spawnLoadAsync(String name) async {
final asset = await _loadAsync(name);
2023-09-19 22:33:45 +00:00
_loaded[name] = asset;
}
2023-09-06 03:11:15 +00:00
}
final assets = Assets();
ui.Image? getImageIfAvailable(String name) {
return assets.getImageIfAvailable(name);
}
2023-09-20 02:19:26 +00:00
Vaults? getVaultsIfAvailable(String name) {
return assets.getVaultsIfAvailable(name);
2023-09-20 02:19:26 +00:00
}