Skip to content

Commit

Permalink
trying to add sqlite caching functionality to cache firebase data
Browse files Browse the repository at this point in the history
  • Loading branch information
konstantinPopovskikh committed Sep 21, 2021
1 parent e76ba79 commit 3bce4e5
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 8 deletions.
32 changes: 32 additions & 0 deletions lib/provider/api.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import 'dart:convert';
import 'dart:ffi';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/provider/database.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart' show kIsWeb;
Expand All @@ -13,6 +15,36 @@ class ApiProvider {
return _getFromDB();
}

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

return value;
} else {
return callFirestore();

// return _getFromApi();
}
});
}

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 addBatchOfFirestore(list: array);
return array;
}

Future _getFromDB() async {
return readCache().then((value) {
if (value.isNotEmpty) {
Expand Down
14 changes: 13 additions & 1 deletion lib/provider/database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,20 @@ Future<Database> cacheDatabase() async {
//read data
Future<List<Map>> readCache() async {
final db = await cacheDatabase();
var cache = db.query('cache');
print('db entries: $cache');

return db.query('cache');
return cache;
}

Future addBatchOfFirestore({required List<Map<String, dynamic>> list}) async {
final db = await cacheDatabase();
final batch = db.batch();
for (var item in list) {
batch.insert('cache', item, conflictAlgorithm: ConflictAlgorithm.replace);
}
await batch.commit(noResult: true);
print('batch insert complete');
}

// add entry
Expand Down
12 changes: 9 additions & 3 deletions lib/provider/sql_queries.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
class Queries {
// String createCacheTable = '''
// CREATE TABLE IF NOT EXISTS cache (
// id INTEGER PRIMARY KEY,
// name TEXT,
// email TEXT,
// body TEXT
// );
// ''';
String createCacheTable = '''
CREATE TABLE IF NOT EXISTS cache (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT,
body TEXT
name TEXT
);
''';
String dropCacheTable = 'DROP TABLE cache';
Expand Down
26 changes: 25 additions & 1 deletion lib/screen/firestore_page.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/provider/database.dart';
import 'package:flutter/material.dart';

class FirestoreDataPage extends StatefulWidget {
Expand All @@ -12,6 +13,9 @@ class _FirestoreDataPageState extends State<FirestoreDataPage> {
final textController = TextEditingController();

void addEntry() {
if (textController.text == '') {
return;
}
FirebaseFirestore.instance
.collection('flutter-caching')
.add({'name': textController.text});
Expand All @@ -37,12 +41,32 @@ class _FirestoreDataPageState extends State<FirestoreDataPage> {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
} else {
print(snapshot.data!.docs.length);
var data = snapshot.data!.docs.map((e) {
return {'name': e['name']};
}).toList();
// cleanDB();
addBatchOfFirestore(list: data);
var db = readCache().then((value) {
return value;
// if (value.isNotEmpty) {
// // print('reading from db');
// // print('reading from db');
// // return Text('database has data');
// }
// print(value);
});

print('db: $db');
// readCache();

// print(data);
return ListView(
children: snapshot.data!.docs.map((e) {
return ListTile(
title: Text(e['name']),
trailing: IconButton(
icon: Icon(Icons.delete),
icon: const Icon(Icons.delete),
onPressed: () {
e.reference.delete();
},
Expand Down
124 changes: 124 additions & 0 deletions lib/screen/firestore_page_future.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fetchingapp/provider/api.dart';
import 'package:fetchingapp/provider/database.dart';
import 'package:flutter/material.dart';

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

@override
_FutureFireStoreState createState() => _FutureFireStoreState();
}

class _FutureFireStoreState extends State<FutureFireStore> {
final textController = TextEditingController();

void addEntry() {
// if (textController.text == '') {
// return;
// }
FirebaseFirestore.instance
.collection('flutter-caching')
.add({'name': textController.text});
textController.clear();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Firestore Data'),
),
body: Column(
children: [
Expanded(
child: Center(
child: FutureBuilder(
future: ApiProvider().getDataForFirestore(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
} else {
// return Text(snapshot.data.toString());
return ListView.builder(
itemCount: (snapshot.data as dynamic).length,
itemBuilder: (context, index) {
final entry = (snapshot.data as dynamic)[index];
return ListTile(
title: Text(entry['name'].toString()),
leading: Icon(Icons.plus_one),
);
});
}
}),
)),
TextField(
controller: textController,
onEditingComplete: () {
addEntry();
},
decoration: InputDecoration(
prefixIcon: const Icon(Icons.add_circle),
labelText: "Input new value and click Save:",
suffixIcon: IconButton(
icon: const Icon(Icons.save),
splashColor: Colors.blue,
tooltip: "Post message",
onPressed: () {
FirebaseFirestore.instance
.collection('flutter-caching')
.add({'name': textController.text});
textController.clear();
},
))),
],
),
);
}
}

// StreamBuilder(
// stream: FirebaseFirestore.instance
// .collection('flutter-caching')
// .orderBy('name')
// .snapshots(),
// builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
// if (!snapshot.hasData) {
// return const Center(child: CircularProgressIndicator());
// } else {
// print(snapshot.data!.docs.length);
// var data = snapshot.data!.docs.map((e) {
// return {'name': e['name']};
// }).toList();
// // cleanDB();
// addBatchOfFirestore(list: data);
// var db = readCache().then((value) {
// return value;
// // if (value.isNotEmpty) {
// // // print('reading from db');
// // // print('reading from db');
// // // return Text('database has data');
// // }
// // print(value);
// });

// print('db: $db');
// // readCache();

// // print(data);
// return ListView(
// children: snapshot.data!.docs.map((e) {
// return ListTile(
// title: Text(e['name']),
// trailing: IconButton(
// icon: const Icon(Icons.delete),
// onPressed: () {
// e.reference.delete();
// },
// ),
// );
// }).toList(),
// );
// }
// },
// ),
4 changes: 2 additions & 2 deletions lib/screen/home_page.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'package:fetchingapp/provider/database.dart';
import 'package:fetchingapp/provider/google_authentication.dart';
import 'package:fetchingapp/screen/firestore_page.dart';
import 'package:fetchingapp/screen/firestore_page_future.dart';
import 'package:fetchingapp/screen/login_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fetchingapp/screen/data_page.dart';

class HomePage extends StatelessWidget {
const HomePage(this.user, {Key? key}) : super(key: key);
Expand Down Expand Up @@ -40,7 +40,7 @@ class HomePage extends StatelessWidget {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const FirestoreDataPage()),
builder: (context) => const FutureFireStore()),
);
},
),
Expand Down
2 changes: 1 addition & 1 deletion lib/screen/login_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class _LoginPageState extends State<LoginPage> {

@override
Widget build(BuildContext context) {
FirebaseService().signOutFromGoogle();
// FirebaseService().signOutFromGoogle();
return Scaffold(
appBar: AppBar(
title: const Text('Login Screen'),
Expand Down

0 comments on commit 3bce4e5

Please sign in to comment.