48 lines
1.4 KiB
Dart
48 lines
1.4 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:aesthetica_wallpaper/models/recipe.dart';
|
|
|
|
class RecipeProvider with ChangeNotifier {
|
|
final String _storageKey = "aesthetica_recipes";
|
|
List<Recipe> _recipes = [];
|
|
|
|
List<Recipe> get recipes => _recipes;
|
|
|
|
// 从 SharedPreferences 加载配方
|
|
Future<void> loadRecipes() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final List<String> recipeStrings = prefs.getStringList(_storageKey) ?? [];
|
|
_recipes = recipeStrings
|
|
.map((str) => Recipe.fromJsonString(str))
|
|
.toList()
|
|
.reversed
|
|
.toList(); // 反转,让最新的在最前面
|
|
notifyListeners();
|
|
}
|
|
|
|
// 保存所有配方到 SharedPreferences
|
|
Future<void> _save() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final List<String> recipeStrings = _recipes
|
|
.map((r) => r.toJsonString())
|
|
.toList();
|
|
await prefs.setStringList(_storageKey, recipeStrings);
|
|
}
|
|
|
|
// 添加一个新配方
|
|
Future<void> addRecipe(Recipe recipe) async {
|
|
// 确保 ID 是唯一的
|
|
recipe.id = DateTime.now().millisecondsSinceEpoch.toString();
|
|
_recipes.insert(0, recipe); // 插入到最前面
|
|
await _save();
|
|
notifyListeners();
|
|
}
|
|
|
|
// 删除一个配方
|
|
Future<void> deleteRecipe(String id) async {
|
|
_recipes.removeWhere((r) => r.id == id);
|
|
await _save();
|
|
notifyListeners();
|
|
}
|
|
}
|