-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_storage_example.dart
More file actions
112 lines (98 loc) · 2.77 KB
/
json_storage_example.dart
File metadata and controls
112 lines (98 loc) · 2.77 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:tiny_db/tiny_db.dart';
void main() async {
final tempDir = Directory(
'${Directory.systemTemp.path}/tiny_db_example',
);
if (!await tempDir.exists()) {
await tempDir.create(recursive: true);
}
final dbPath = '${tempDir.path}/example_db.json';
if (kDebugMode) {
print('Database will be stored at: $dbPath');
}
final dbFile = File(dbPath);
if (await dbFile.exists()) {
await dbFile.delete();
}
final db = TinyDb(JsonStorage(dbPath, indentAmount: 2, createDirs: true));
try {
await db.insert({
'type': 'note',
'title': 'Shopping List',
'items': ['Milk', 'Eggs', 'Bread'],
});
await db.insert({
'type': 'note',
'title': 'Todo',
'items': ['Buy groceries', 'Call mom'],
});
final settings = db.table('settings');
await settings.insert({
'theme': 'dark',
'notifications': true,
'preferences': {'fontSize': 14, 'language': 'en', 'autoSave': true},
});
final profiles = db.table('profiles');
await profiles.insert({
'username': 'alice',
'email': 'alice@example.com',
'lastLogin': DateTime.now().toIso8601String(),
'tags': ['admin', 'verified'],
});
await profiles.insert({
'username': 'bob',
'email': 'bob@example.com',
'lastLogin': DateTime.now().toIso8601String(),
'tags': ['user'],
});
await profiles.update(
UpdateOperations()
.push('tags', 'active')
.set('lastActive', DateTime.now().toIso8601String()),
where('username').equals('alice'),
);
if (kDebugMode) {
print('\nDefault table contents:');
}
final defaultDocs = await db.all();
for (final doc in defaultDocs) {
if (kDebugMode) {
print(' - ${doc['title']} (${doc['type']})');
}
}
if (kDebugMode) {
print('\nSettings table contents:');
}
final settingsDocs = await settings.all();
for (final doc in settingsDocs) {
if (kDebugMode) {
print(
' - Theme: ${doc['theme']}, Notifications: ${doc['notifications']}',
);
}
}
if (kDebugMode) {
print('\nProfiles table contents:');
}
final profileDocs = await profiles.all();
for (final doc in profileDocs) {
if (kDebugMode) {
print(' - ${doc['username']} (${doc['email']})');
print(' Tags: ${doc['tags'].join(', ')}');
}
}
if (kDebugMode) {
print('\nDatabase saved to: $dbPath');
print('You can open this file to see the JSON structure.');
}
final jsonContent = await File(dbPath).readAsString();
if (kDebugMode) {
print('\nRaw JSON content:');
print(jsonContent);
}
} finally {
await db.close();
}
}