This repository was archived by the owner on Aug 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathutils.dart
66 lines (57 loc) · 1.99 KB
/
utils.dart
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
63
64
65
66
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../../../models/restaurant.dart';
class Utils {
static Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
static Future<File> get _localFile async {
final path = await _localPath;
return File('$path/favorites.json');
}
static Future<List<Restaurant>> loadFavorites() async {
try {
final file = await _localFile;
if (await file.exists()) {
final contents = await file.readAsString();
final List<dynamic> jsonData = json.decode(contents);
return jsonData.map((item) => Restaurant.fromJson(item)).toList();
}
return [];
} catch (e) {
// Handle the exception, possibly logging or showing a message to the user
return [];
}
}
static Future<void> addFavorite(Restaurant restaurant) async {
final favorites = await loadFavorites();
if (!favorites.any((element) => element.id == restaurant.id)) {
favorites.add(restaurant);
await _saveToFile(favorites);
}
}
static Future<void> removeFavorite(String id) async {
final favorites = await loadFavorites();
favorites.removeWhere((restaurant) => restaurant.id == id);
await _saveToFile(favorites);
}
static Future<void> _saveToFile(List<Restaurant> restaurants) async {
final file = await _localFile;
final String jsonString =
json.encode(restaurants.map((e) => e.toJson()).toList());
await file.writeAsString(jsonString);
}
static Future<void> toggleFavorite(Restaurant restaurant) async {
final favorites = await loadFavorites();
final existingIndex = favorites.indexWhere((r) => r.id == restaurant.id);
if (existingIndex >= 0) {
// Restaurant is already a favorite, remove it
await removeFavorite(restaurant.id!);
} else {
// Restaurant is not a favorite, add it
await addFavorite(restaurant);
}
}
}