aboutsummaryrefslogtreecommitdiff
path: root/lib/models/data/recipe_data_class.dart
blob: 3f707bc4460db48c329d664b222aa4a047214d8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import 'dart:convert';

import 'package:kulinar_app/models/recipe_class.dart';
import 'package:kulinar_app/util/storage_handler.dart';

class RecipeData {
  static List<Recipe> remoteRecipeList = [];
  static List<Recipe> recipeList = [];

  static Future<void> save() async {
    await StorageHandler.store("recipes", encode());
  }

  static Future<void> load() async {
    decode(await StorageHandler.fetch("recipes") ?? "[]");
  }

  static String encode() {
    List<Map<String, dynamic>> _tempList = [];

    recipeList.forEach((element) {
      Map<String, dynamic> _map = Map<String, dynamic>();

      _map["title"] = element.title;
      _map["description"] = element.description;
      _map["favorite"] = element.favorite;
      _map["rating"] = element.rating;
      _map["image"] = element.image;

      _tempList.add(_map);
    });

    return jsonEncode(_tempList);
  }

  static void decode(String data) {
    final _result = jsonDecode(data);

    if (_result.isEmpty) return;

    recipesIdentical(Recipe a, Recipe b) {
      if (a.title != b.title) return false;
      if (a.description != b.description) return false;

      return true;
    }

    _result.forEach((item) {
      Recipe recipe = Recipe(
        title: item["title"],
        description: item["description"],
        favorite: item["favorite"],
        rating: item["rating"],
        image: item["image"],
      );

      if (RecipeData.recipeList.where((element) => recipesIdentical(element, recipe)).isEmpty) recipeList.add(recipe);
    });

    save();
  }
}