是否可以将 List<Model>? modelName;
这样的模型列表作为 Hive
本地存储中的 json 文件?
这是我的FavoriteRecipeModel
class FavoriteRecipeModel {
RecipeModel? recipe;
FavoriteRecipeModel({this.recipe});
factory FavoriteRecipeModel.fromJson(Map<String, dynamic> json) =>
FavoriteRecipeModel(
recipe: json["recipe"] == null ? null : json["recipe"],
);
Map<String, dynamic> toJson() => {
"recipe": recipe == null ? null : recipe,
};
}
如您所见,我正在使用另一个名为 RecipeModel 的模型。 RecipeModel 将加载一个类似于以下内容的 json 文件:
{
"recipeId": "1",
"recipeName": "Burger",
"recipeThumbnailLink":"#",
"recipeVideoLink": "#",
"recipeAuthor": "John Doe",
"category":"Fast Food",
"time": "15 min",
"ingredients": [
{
"id": "ingredient1",
"name": "Tomato",
"amount": "2 slices",
"ingredientThumbnailLink": ""
},
{
"id": "ingredient2",
"name": "Onion",
"amount": "$ slices",
"ingredientThumbnailLink": ""
},
{
"id": "ingredient3",
"name": "Spinach",
"amount": "2 pieces",
"ingredientThumbnailLink": ""
}
],
"recipeSteps": [
{
"id": "step1",
"name": "Tomato",
"stepThumbnailLink": ""
},
{
"id": "step2",
"name": "Onion",
"stepThumbnailLink": ""
},
{
"id": "step3",
"name": "Spinach",
"stepThumbnailLink": ""
}
]
},
因此,考虑到这两个因素,可以将整个配方保存为 List<RecipeModel>?
我需要编写一个函数来保存上述 json 数据。一个用户可以有多个最喜欢的食谱。是否可以根据模型将上述数据保存为json
格式?
我的整个 RecipeModel 可以在 here 中找到。
答案 0 :(得分:1)
很可能将模型存储为 json。您必须实现 serialization/deserialization
以在 RecipeModel
和 json map
之间进行转换。我建议您使用 json_serializable 包来为您解决这个问题。
另一种方法是,如果您想将数据完全存储为 List<RecipeModel>
,那么您可以使用 Hive 来实现,但您必须为您的模型实现自定义 TypeAdaptor
.
一点也不难,Reso Coder 的这个 tutorial 是一个好的开始。