Refresh cached training catalog safely

This commit is contained in:
Hamza-Ayed
2026-10-04 01:50:52 +03:00
parent b1e5aa2f98
commit 66efcdac6a
2 changed files with 80 additions and 52 deletions
+14 -3
View File
@@ -15,12 +15,14 @@ class TrainingPlanService {
final AuthService _auth;
final http.Client _client;
Future<List<TrainingPlan>> readCachedPlans() async {
final prefs = await SharedPreferences.getInstance();
return _decodeCache(prefs.getString(_cacheKey));
}
Future<TrainingCatalogResult> fetchPlans({bool refresh = false}) async {
final prefs = await SharedPreferences.getInstance();
final cached = _decodeCache(prefs.getString(_cacheKey));
if (!refresh && cached.isNotEmpty) {
return TrainingCatalogResult(plans: cached, fromCache: true);
}
if (!_auth.isApiConfigured) {
return TrainingCatalogResult(
plans: cached,
@@ -46,6 +48,15 @@ class TrainingPlanService {
.map(TrainingPlan.fromJson)
.where((plan) => plan.uuid.isNotEmpty)
.toList(growable: false);
// An empty catalog can be an unpublished/temporarily incomplete response.
// Keep the last known good catalog rather than erasing offline content.
if (plans.isEmpty && cached.isNotEmpty) {
return TrainingCatalogResult(
plans: cached,
fromCache: true,
message: 'لا توجد خطط منشورة حاليًا؛ نعرض آخر نسخة محفوظة.',
);
}
await prefs.setString(
_cacheKey,
jsonEncode(plans.map(_toCacheJson).toList(growable: false)),