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 _postsKey = 'patbond_posts'; static const _locationWeatherKey = 'patbond_location_weather'; /// 首页问候卡 / 创作页 / 主壳头像仍消费的 demo 宠物(T2-12 起档案 /// Tab 已切独立 pets feature 真实数据;此 demo 随后续工单收敛)。 PetProfile pet = initialPet; List posts = List.from(initialPosts); LocationWeather locationWeather = initialLocationWeather; bool isReady = false; Future load() async { try { final preferences = await SharedPreferences.getInstance(); final savedPet = preferences.getString(_petKey); final savedPosts = preferences.getString(_postsKey); final savedLocationWeather = preferences.getString(_locationWeatherKey); if (savedPet != null) { pet = PetProfile.fromJson(jsonDecode(savedPet) as Map); } if (savedPosts != null) { posts = (jsonDecode(savedPosts) as List) .map((item) => PostModel.fromJson(item as Map)) .toList(); } if (savedLocationWeather != null) { locationWeather = LocationWeather.fromJson( jsonDecode(savedLocationWeather) as Map, ); } } catch (error, stackTrace) { debugPrint('读取本地数据失败,已使用默认数据:$error\n$stackTrace'); pet = initialPet; posts = List.from(initialPosts); locationWeather = initialLocationWeather; } finally { isReady = true; notifyListeners(); } } Future updatePost(PostModel value) async { final index = posts.indexWhere((post) => post.id == value.id); if (index == -1) return; posts[index] = value; posts = List.from(posts); notifyListeners(); await _savePosts(); } Future publishPost(PostModel value) async { posts = [value, ...posts]; notifyListeners(); await _savePosts(); } Future updateLocationWeather(LocationWeather value) async { locationWeather = value; notifyListeners(); await _save(_locationWeatherKey, value.toJson()); } Future resetDemoData() async { pet = initialPet; posts = List.from(initialPosts); locationWeather = initialLocationWeather; notifyListeners(); final preferences = await SharedPreferences.getInstance(); await Future.wait([ preferences.remove(_petKey), preferences.remove(_postsKey), preferences.remove(_locationWeatherKey), ]); } Future _savePosts() { return _save(_postsKey, posts.map((post) => post.toJson()).toList()); } 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'); } } }