Skip to content

Commit

Permalink
caching into SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
konstantinPopovskikh committed Sep 23, 2021
1 parent 6abd7e9 commit 9ca519d
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 119 deletions.
12 changes: 6 additions & 6 deletions lib/backend/database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@ import 'package:fetchingapp/backend/sql_queries.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

Future<Database> cacheDatabase() async {
Future<Database> initializeDB() async {
return openDatabase(join(await getDatabasesPath(), 'cache_database.db'),
onCreate: (db, version) {
return db.execute(Queries().createCacheTable);
}, version: 1);
}

Future insertSQLite({required Map<String, dynamic> item}) async {
final db = await cacheDatabase();
final db = await initializeDB();
db.insert('cache', item);
}

Future updateSQLite({required Map<String, dynamic> item}) async {
final db = await cacheDatabase();
final db = await initializeDB();
db.update('cache', item, where: 'doc_id = ?', whereArgs: [item['doc_id']]);
}

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

Future insertBatchSQLite({required List<Map<String, dynamic>> list}) async {
final db = await cacheDatabase();
final db = await initializeDB();
final batch = db.batch();
for (var item in list) {
batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
Expand All @@ -34,7 +34,7 @@ Future insertBatchSQLite({required List<Map<String, dynamic>> list}) async {
}

Future cleanDB() async {
final db = await cacheDatabase();
final db = await initializeDB();
db.execute(Queries().dropCacheTable);
db.execute(Queries().createCacheTable);
}
Expand Down
109 changes: 19 additions & 90 deletions lib/backend/firestore_listener.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/backend/database.dart';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/backend/database.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart' show kIsWeb;

class FirestoreChanges extends ChangeNotifier {
List<Map<String, dynamic>> list = [];
Expand Down Expand Up @@ -45,94 +40,28 @@ class FirestoreChanges extends ChangeNotifier {
notifyListeners();
});
}

Future<List<Map>> readSQLiteCache() async {
final db = await cacheDatabase();
var cache = db.query('cache');
var value = cache.then((value) {

Future<List<Map>> readSQLiteCache() async {
final db = await initializeDB();
var cache = db.query('cache');
var value = cache.then((value) {
print(value.length);
return value;
});
return value;
});
return value;
}
}


removeDocFromFirebase(String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.delete();
}

// class Firestore {
// Future getData() async {
// return readCache().then((value) async {
// return value;
// });
// }
// }

class ApiProvider {
// final url = 'https://jsonplaceholder.typicode.com/comments';

// Future getData() async {
// if (kIsWeb) {
// return _getFromApi();
// }
// return _getFromDB();
// }

// Future getDataForFirestore() async {
// return readSQLiteCache().then((value) async {
// if (value.isNotEmpty) {
// print('READING FROM DB, NUMBER OF ENTRIES: ${value.length}');
// callFirestore();
// return value;
// } else {
// return callFirestore();
// }
// });
// }

Future callFirestore() async {
cleanDB();
print('fetching from network');
var data = await FirebaseFirestore.instance
.collection('flutter-caching')
.orderBy('name')
.get();
var array = data.docs.map((e) {
return {'name': e['name']};
}).toList();
// await insertSQLite(list: array);
return array;
}

// Future _getFromDB() async {
// return readJsonCache().then((value) {
// if (value.isNotEmpty) {
// print('reading from db');
// return value;
// } else {
// print('fetching from network');
// return _getFromApi();
// }
// });
// }

// Future _getFromApi() async {
// try {
// final req = await http.get(Uri.parse(url));
// if (req.statusCode == 200) {
// final body = req.body;
// final jsonDecoded = json.decode(body);

// // cache data
// if (!kIsWeb) {
// await cleanDB();
// await addBatchOfEntries(entries: jsonDecoded);
// }
// return json.decode(body);
// } else {
// return json.decode(req.body);
// }
// } catch (e) {
// // ignore
// }
// }
// }
editDocInFirebase(String value, String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.update({'name': value});
}
30 changes: 14 additions & 16 deletions lib/screens/firestore_collection.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/backend/database.dart';
import 'package:fetchingapp/backend/firestore_listener.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
Expand Down Expand Up @@ -32,20 +31,6 @@ class _FirestoreCollectionCachingState
}
}

removeDocFromFirebase(String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.delete();
}

editDocInFirebase(String value, String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.update({'name': value});
}

class DocList extends StatefulWidget {
const DocList({Key? key}) : super(key: key);

Expand Down Expand Up @@ -97,7 +82,7 @@ class _DocListState extends State<DocList> {
Widget inputfield() {
final textController = TextEditingController();

void addDocToFirebase() {
addDocToFirebase() {
// if (textController.text == '') {
// return;
// }
Expand Down Expand Up @@ -126,6 +111,19 @@ Widget inputfield() {
)));
}

removeDocFromFirebase(String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.delete();
}

editDocInFirebase(String value, String doc) async {
await FirebaseFirestore.instance
.collection('flutter-caching')
.doc(doc)
.update({'name': value});
}


// Widget list({required BuildContext context}) {
Expand Down
6 changes: 0 additions & 6 deletions lib/screens/home.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import 'package:fetchingapp/backend/database.dart';
import 'package:fetchingapp/backend/google_authentication.dart';
import 'package:fetchingapp/screens/firestore_collection.dart';
import 'package:fetchingapp/screens/login.dart';
Expand Down Expand Up @@ -34,11 +33,6 @@ class HomePage extends StatelessWidget {
'Firestore Collection',
style: TextStyle(fontSize: 25),
)),
// ElevatedButton(
// onPressed: () {
// readCache();
// },
// child: const Text('Read Cache'))
],
),
);
Expand Down
1 change: 0 additions & 1 deletion lib/screens/login.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ class LoginPage extends StatefulWidget {
class _LoginPageState extends State<LoginPage> {
@override
Widget build(BuildContext context) {
// FirebaseService().signOutFromGoogle();
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
Expand Down

0 comments on commit 9ca519d

Please sign in to comment.