Skip to content

Commit 6abd7e9

Browse files
almost working example of SQLite caching with Provider
1 parent 6517295 commit 6abd7e9

File tree

11 files changed

+205
-457
lines changed

11 files changed

+205
-457
lines changed

lib/backend/api.dart

Lines changed: 0 additions & 78 deletions
This file was deleted.

lib/backend/database.dart

Lines changed: 6 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,42 @@
1-
import 'package:fetchingapp/model/data_model.dart';
21
import 'package:fetchingapp/backend/sql_queries.dart';
3-
import 'package:flutter/foundation.dart';
42
import 'package:path/path.dart';
53
import 'package:sqflite/sqflite.dart';
64

75
Future<Database> cacheDatabase() async {
86
return openDatabase(join(await getDatabasesPath(), 'cache_database.db'),
97
onCreate: (db, version) {
10-
return db.execute(Queries().createCacheTable + Queries().jsonCache);
8+
return db.execute(Queries().createCacheTable);
119
}, version: 1);
1210
}
1311

14-
//read data
15-
Future<List<Map>> readCache() async {
16-
final db = await cacheDatabase();
17-
var cache = db.query('cache');
18-
cache.then((value) {
19-
print(value);
20-
});
21-
22-
return cache;
23-
}
24-
25-
Future<List<Map>> readJsonCache() async {
26-
final db = await cacheDatabase();
27-
var cache = db.query('jsoncache');
28-
29-
return cache;
30-
}
31-
3212
Future insertSQLite({required Map<String, dynamic> item}) async {
3313
final db = await cacheDatabase();
3414
db.insert('cache', item);
35-
// final batch = db.batch();
36-
// for (var item in list) {
37-
// batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
38-
// }
39-
// await batch.commit(noResult: true);
40-
}
41-
42-
Future insertBatchSQLite({required List<Map<String, dynamic>> list}) async {
43-
final db = await cacheDatabase();
44-
// db.insert('cache', item);
45-
final batch = db.batch();
46-
for (var item in list) {
47-
batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
48-
}
49-
await batch.commit(noResult: true);
5015
}
5116

5217
Future updateSQLite({required Map<String, dynamic> item}) async {
5318
final db = await cacheDatabase();
5419
db.update('cache', item, where: 'doc_id = ?', whereArgs: [item['doc_id']]);
55-
// final batch = db.batch();
56-
// for (var item in list) {
57-
// batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
58-
// }
59-
// await batch.commit(noResult: true);
6020
}
6121

6222
Future deleteSQLite({required Map<String, dynamic> item}) async {
6323
final db = await cacheDatabase();
6424
db.delete('cache', where: 'doc_id = ?', whereArgs: [item['doc_id']]);
6525
}
6626

67-
// add entry
68-
Future addBatchOfEntries({required List<dynamic> entries}) async {
27+
Future insertBatchSQLite({required List<Map<String, dynamic>> list}) async {
6928
final db = await cacheDatabase();
7029
final batch = db.batch();
71-
for (var item in entries) {
72-
final entry =
73-
DataModel(name: item['name'], body: item['body'], email: item['email']);
74-
75-
batch.insert('jsoncache', entry.toMap(),
76-
conflictAlgorithm: ConflictAlgorithm.replace);
30+
for (var item in list) {
31+
batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
7732
}
7833
await batch.commit(noResult: true);
7934
}
8035

8136
Future cleanDB() async {
82-
if (kIsWeb) {
83-
return;
84-
}
8537
final db = await cacheDatabase();
8638
db.execute(Queries().dropCacheTable);
87-
db.execute(Queries().dropJsonTable);
8839
db.execute(Queries().createCacheTable);
89-
db.execute(Queries().jsonCache);
90-
// readCache();
9140
}
41+
42+

lib/backend/firestore_listener.dart

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import 'package:cloud_firestore/cloud_firestore.dart';
22
import 'package:fetchingapp/backend/database.dart';
33
import 'package:flutter/foundation.dart';
4+
import 'dart:convert';
5+
import 'package:cloud_firestore/cloud_firestore.dart';
6+
import 'package:fetchingapp/backend/database.dart';
7+
import 'package:http/http.dart' as http;
8+
import 'package:flutter/foundation.dart' show kIsWeb;
49

510
class FirestoreChanges extends ChangeNotifier {
611
List<Map<String, dynamic>> list = [];
@@ -37,9 +42,97 @@ class FirestoreChanges extends ChangeNotifier {
3742
'Data: ${change.doc.data()}\n\n');
3843
}
3944
}
40-
// notifyListeners();
45+
notifyListeners();
4146
});
4247
}
48+
49+
Future<List<Map>> readSQLiteCache() async {
50+
final db = await cacheDatabase();
51+
var cache = db.query('cache');
52+
var value = cache.then((value) {
53+
return value;
54+
});
55+
return value;
4356
}
4457

4558

59+
}
60+
61+
// class Firestore {
62+
// Future getData() async {
63+
// return readCache().then((value) async {
64+
// return value;
65+
// });
66+
// }
67+
// }
68+
69+
class ApiProvider {
70+
// final url = 'https://jsonplaceholder.typicode.com/comments';
71+
72+
// Future getData() async {
73+
// if (kIsWeb) {
74+
// return _getFromApi();
75+
// }
76+
// return _getFromDB();
77+
// }
78+
79+
// Future getDataForFirestore() async {
80+
// return readSQLiteCache().then((value) async {
81+
// if (value.isNotEmpty) {
82+
// print('READING FROM DB, NUMBER OF ENTRIES: ${value.length}');
83+
// callFirestore();
84+
// return value;
85+
// } else {
86+
// return callFirestore();
87+
// }
88+
// });
89+
// }
90+
91+
Future callFirestore() async {
92+
cleanDB();
93+
print('fetching from network');
94+
var data = await FirebaseFirestore.instance
95+
.collection('flutter-caching')
96+
.orderBy('name')
97+
.get();
98+
var array = data.docs.map((e) {
99+
return {'name': e['name']};
100+
}).toList();
101+
// await insertSQLite(list: array);
102+
return array;
103+
}
104+
105+
// Future _getFromDB() async {
106+
// return readJsonCache().then((value) {
107+
// if (value.isNotEmpty) {
108+
// print('reading from db');
109+
// return value;
110+
// } else {
111+
// print('fetching from network');
112+
// return _getFromApi();
113+
// }
114+
// });
115+
// }
116+
117+
// Future _getFromApi() async {
118+
// try {
119+
// final req = await http.get(Uri.parse(url));
120+
// if (req.statusCode == 200) {
121+
// final body = req.body;
122+
// final jsonDecoded = json.decode(body);
123+
124+
// // cache data
125+
// if (!kIsWeb) {
126+
// await cleanDB();
127+
// await addBatchOfEntries(entries: jsonDecoded);
128+
// }
129+
// return json.decode(body);
130+
// } else {
131+
// return json.decode(req.body);
132+
// }
133+
// } catch (e) {
134+
// // ignore
135+
// }
136+
// }
137+
// }
138+
}

lib/backend/sql_queries.dart

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
class Queries {
2-
// String createCacheTable = '''
3-
42
String createCacheTable = '''
53
CREATE TABLE IF NOT EXISTS cache (
64
id INTEGER PRIMARY KEY,
@@ -9,15 +7,5 @@ class Queries {
97
);
108
''';
119

12-
String jsonCache = '''
13-
CREATE TABLE IF NOT EXISTS jsoncache (
14-
id INTEGER PRIMARY KEY,
15-
name TEXT,
16-
email TEXT,
17-
body TEXT
18-
);
19-
''';
20-
2110
String dropCacheTable = 'DROP TABLE cache';
22-
String dropJsonTable = 'DROP TABLE jsoncache';
2311
}

lib/model/data_model.dart

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)