Refresh cached training catalog safely
This commit is contained in:
@@ -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)),
|
||||
|
||||
Reference in New Issue
Block a user