import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:patbond_flutter/data/demo_data.dart'; import 'package:patbond_flutter/models/models.dart'; import 'package:shared_preferences/shared_preferences.dart'; class AppState extends ChangeNotifier { static const _petKey = 'patbond_pet'; static const _locationWeatherKey = 'patbond_location_weather'; /// 首页问候卡 / 创作页 / 主壳头像仍消费的 demo 宠物(T2-12 起档案 /// Tab 已切独立 pets feature 真实数据;此 demo 随后续工单收敛)。 /// /// **demo 帖子列表已于 T3-17 退役**:Feed / 详情页自 T3-14/15 起消费 /// community 真实数据,发布页自 T3-17 起走真实两步上传 + 建草稿/迁移 /// 发布,`posts` / `publishPost` / `updatePost` 与其 /// shared_preferences 持久化一并删除(03 号评估 §1.1 判定)。 PetProfile pet = initialPet; LocationWeather locationWeather = initialLocationWeather; bool isReady = false; Future load() async { try { final preferences = await SharedPreferences.getInstance(); final savedPet = preferences.getString(_petKey); final savedLocationWeather = preferences.getString(_locationWeatherKey); if (savedPet != null) { pet = PetProfile.fromJson(jsonDecode(savedPet) as Map); } if (savedLocationWeather != null) { locationWeather = LocationWeather.fromJson( jsonDecode(savedLocationWeather) as Map, ); } } catch (error, stackTrace) { debugPrint('读取本地数据失败,已使用默认数据:$error\n$stackTrace'); pet = initialPet; locationWeather = initialLocationWeather; } finally { isReady = true; notifyListeners(); } } Future updateLocationWeather(LocationWeather value) async { locationWeather = value; notifyListeners(); await _save(_locationWeatherKey, value.toJson()); } Future resetDemoData() async { pet = initialPet; locationWeather = initialLocationWeather; notifyListeners(); final preferences = await SharedPreferences.getInstance(); await Future.wait([ preferences.remove(_petKey), preferences.remove(_locationWeatherKey), ]); } Future _save(String key, Object value) async { try { final preferences = await SharedPreferences.getInstance(); await preferences.setString(key, jsonEncode(value)); } catch (error, stackTrace) { debugPrint('保存本地数据失败:$error\n$stackTrace'); } } }