getOptimizedStyleJson static method
Fetches, optimizes, and caches the style JSON.
Caching strategy:
- Check in-memory cache first (instant).
- Check disk cache if fresh (< 24h), return immediately.
- Fetch from network, optimize, save to disk + memory.
- If network fails, fall back to stale disk cache (offline support).
Implementation
static Future<String> getOptimizedStyleJson(String name, {bool enable3D = false}) async {
// Auto-cleanup old version caches in background
_cleanOldVersionCaches();
final cacheKey = '${name}_${enable3D ? '3d' : '2d'}';
// 1. In-memory hit (fastest)
if (_memoryCache.containsKey(cacheKey)) {
return _memoryCache[cacheKey]!;
}
// 2. Disk cache hit (fast)
try {
final cacheFile = await _getCacheFile(name, enable3D: enable3D);
if (_isCacheFresh(cacheFile)) {
final cached = await cacheFile.readAsString();
_memoryCache[cacheKey] = cached;
return cached;
}
} catch (_) {
// Disk read failed, continue to network
}
// 3. Network fetch
try {
final optimized = await _fetchAndOptimize(name, enable3D: enable3D);
// Save to disk + memory
try {
final cacheFile = await _getCacheFile(name, enable3D: enable3D);
await cacheFile.writeAsString(optimized);
} catch (_) {
// Disk write failed, still usable from memory
}
_memoryCache[cacheKey] = optimized;
return optimized;
} catch (e) {
// 4. Offline fallback: use stale cache if available
try {
final cacheFile = await _getCacheFile(name, enable3D: enable3D);
if (cacheFile.existsSync()) {
final stale = await cacheFile.readAsString();
_memoryCache[cacheKey] = stale;
return stale;
}
} catch (_) {
// No cache available at all
}
if (e is PowerMapException) {
rethrow;
}
throw PowerMapException(
code: PowerMapException.styleLoad,
message:
'Failed to load map style "$name" and no local cache was found.',
details: e,
);
}
}