import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; class BeaconCache { static const _keyBeaconData = 'beacon_cache_data'; static const _keyBeaconTimestamp = 'beacon_cache_timestamp'; static const _cacheDuration = Duration(hours: 24); // Cache for 24 hours /// Save beacon list to cache static Future save(Map beacons) async { final prefs = await SharedPreferences.getInstance(); final json = jsonEncode(beacons); await prefs.setString(_keyBeaconData, json); await prefs.setInt(_keyBeaconTimestamp, DateTime.now().millisecondsSinceEpoch); } /// Load beacon list from cache (returns null if expired or not found) static Future?> load() async { final prefs = await SharedPreferences.getInstance(); final timestamp = prefs.getInt(_keyBeaconTimestamp); final data = prefs.getString(_keyBeaconData); if (timestamp == null || data == null) { return null; } // Check if cache is expired final cachedTime = DateTime.fromMillisecondsSinceEpoch(timestamp); if (DateTime.now().difference(cachedTime) > _cacheDuration) { return null; } try { final decoded = jsonDecode(data) as Map; return decoded.map((k, v) => MapEntry(k, v as int)); } catch (e) { return null; } } /// Clear the beacon cache static Future clear() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_keyBeaconData); await prefs.remove(_keyBeaconTimestamp); } }