Skip to content

Commit 9150e98

Browse files
cleaned up code; added all the tests to the main page
1 parent b172503 commit 9150e98

File tree

9 files changed

+141
-90
lines changed

9 files changed

+141
-90
lines changed

lib/main.dart

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import 'package:fetchingapp/screen/home_page.dart';
12
import 'package:fetchingapp/screen/login_page.dart';
3+
import 'package:firebase_auth/firebase_auth.dart';
24
import 'package:flutter/material.dart';
35
import 'package:firebase_core/firebase_core.dart';
46

@@ -14,11 +16,21 @@ class MyApp extends StatelessWidget {
1416
// This widget is the root of your application.
1517
@override
1618
Widget build(BuildContext context) {
19+
User? firebaseUser = FirebaseAuth.instance.currentUser;
20+
21+
Widget firstScreen;
22+
23+
if (firebaseUser != null) {
24+
firstScreen = HomePage(firebaseUser);
25+
} else {
26+
firstScreen = const LoginPage();
27+
}
28+
1729
return MaterialApp(
1830
theme: ThemeData(
1931
primarySwatch: Colors.blue,
2032
),
21-
home: const LoginPage(),
33+
home: firstScreen,
2234
);
2335
}
2436
}

lib/provider/api.dart

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import 'dart:convert';
2-
import 'dart:ffi';
32
import 'package:cloud_firestore/cloud_firestore.dart';
43
import 'package:fetchingapp/provider/database.dart';
54
import 'package:http/http.dart' as http;
@@ -20,7 +19,6 @@ class ApiProvider {
2019
if (value.isNotEmpty) {
2120
print('READING FROM DB, NUMBER OF ENTRIES: ${value.length}');
2221
callFirestore();
23-
print('called firestore');
2422

2523
return value;
2624
} else {
@@ -46,7 +44,7 @@ class ApiProvider {
4644
}
4745

4846
Future _getFromDB() async {
49-
return readCache().then((value) {
47+
return readJsonCache().then((value) {
5048
if (value.isNotEmpty) {
5149
print('reading from db');
5250
return value;
@@ -67,7 +65,6 @@ class ApiProvider {
6765
// cache data
6866
if (!kIsWeb) {
6967
await cleanDB();
70-
print('db cleaned');
7168
await addBatchOfEntries(entries: jsonDecoded);
7269
}
7370
return json.decode(body);

lib/provider/database.dart

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,21 @@ import 'package:sqflite/sqflite.dart';
77
Future<Database> cacheDatabase() async {
88
return openDatabase(join(await getDatabasesPath(), 'cache_database.db'),
99
onCreate: (db, version) {
10-
return db.execute(Queries().createCacheTable);
10+
return db.execute(Queries().createCacheTable + Queries().jsonCache);
1111
}, version: 1);
1212
}
1313

1414
//read data
1515
Future<List<Map>> readCache() async {
1616
final db = await cacheDatabase();
1717
var cache = db.query('cache');
18-
print('db entries: $cache');
18+
19+
return cache;
20+
}
21+
22+
Future<List<Map>> readJsonCache() async {
23+
final db = await cacheDatabase();
24+
var cache = db.query('jsoncache');
1925

2026
return cache;
2127
}
@@ -38,7 +44,7 @@ Future addBatchOfEntries({required List<dynamic> entries}) async {
3844
final entry =
3945
DataModel(name: item['name'], body: item['body'], email: item['email']);
4046

41-
batch.insert('cache', entry.toMap(),
47+
batch.insert('jsoncache', entry.toMap(),
4248
conflictAlgorithm: ConflictAlgorithm.replace);
4349
}
4450
await batch.commit(noResult: true);
@@ -51,5 +57,7 @@ Future cleanDB() async {
5157
}
5258
final db = await cacheDatabase();
5359
db.execute(Queries().dropCacheTable);
60+
db.execute(Queries().dropJsonTable);
5461
db.execute(Queries().createCacheTable);
62+
db.execute(Queries().jsonCache);
5563
}

lib/provider/sql_queries.dart

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
class Queries {
22
// String createCacheTable = '''
3-
// CREATE TABLE IF NOT EXISTS cache (
4-
// id INTEGER PRIMARY KEY,
5-
// name TEXT,
6-
// email TEXT,
7-
// body TEXT
8-
// );
9-
// ''';
3+
104
String createCacheTable = '''
115
CREATE TABLE IF NOT EXISTS cache (
126
id INTEGER PRIMARY KEY,
137
name TEXT
148
);
159
''';
10+
11+
String jsonCache = '''
12+
CREATE TABLE IF NOT EXISTS jsoncache (
13+
id INTEGER PRIMARY KEY,
14+
name TEXT,
15+
email TEXT,
16+
body TEXT
17+
);
18+
''';
19+
1620
String dropCacheTable = 'DROP TABLE cache';
21+
String dropJsonTable = 'DROP TABLE jsoncache';
22+
}
23+
24+
void main() {
25+
print(Queries().createCacheTable + Queries().jsonCache);
1726
}
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import 'package:cloud_firestore/cloud_firestore.dart';
22
import 'package:fetchingapp/provider/api.dart';
3-
import 'package:fetchingapp/provider/database.dart';
43
import 'package:flutter/material.dart';
54

65
class FutureFireStore extends StatefulWidget {
@@ -46,7 +45,7 @@ class _FutureFireStoreState extends State<FutureFireStore> {
4645
final entry = (snapshot.data as dynamic)[index];
4746
return ListTile(
4847
title: Text(entry['name'].toString()),
49-
leading: Icon(Icons.data_usage),
48+
leading: const Icon(Icons.data_usage),
5049
);
5150
});
5251
}
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ class _StreamFireStoreState extends State<StreamFireStore> {
5757
// print(value);
5858
});
5959

60-
print('db: $db');
6160
// readCache();
6261

6362
// print(data);

lib/screen/home_page.dart

Lines changed: 68 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import 'package:fetchingapp/provider/database.dart';
22
import 'package:fetchingapp/provider/google_authentication.dart';
3-
import 'package:fetchingapp/screen/firestore_page_stream.dart';
4-
import 'package:fetchingapp/screen/firestore_page_future.dart';
3+
import 'package:fetchingapp/screen/firestore_stream.dart';
4+
import 'package:fetchingapp/screen/firestore_future.dart';
5+
import 'package:fetchingapp/screen/json_caching.dart';
56
import 'package:fetchingapp/screen/login_page.dart';
67
import 'package:firebase_auth/firebase_auth.dart';
78
import 'package:flutter/material.dart';
@@ -15,63 +16,88 @@ class HomePage extends StatelessWidget {
1516
Widget build(BuildContext context) {
1617
return Scaffold(
1718
appBar: AppBar(
19+
automaticallyImplyLeading: false,
1820
title: const Text('Home Page'),
1921
),
2022
body: Center(
2123
child: Column(
2224
mainAxisAlignment: MainAxisAlignment.center,
2325
crossAxisAlignment: CrossAxisAlignment.center,
2426
children: [
25-
Container(
26-
color: Colors.red,
27-
),
2827
const Text(
2928
'Try getting Firebase data with and without Cache.',
3029
style: TextStyle(fontSize: 20),
3130
textAlign: TextAlign.center,
3231
),
3332
const SizedBox(height: 50),
34-
ElevatedButton(
35-
child: const Text(
36-
'Show Firebase Data',
37-
style: TextStyle(fontSize: 20),
38-
),
39-
onPressed: () {
40-
Navigator.push(
41-
context,
42-
MaterialPageRoute(
43-
builder: (context) => const FutureFireStore()),
44-
);
45-
},
46-
),
33+
testSectionButton(
34+
context: context,
35+
name: 'Future Firestore',
36+
widget: const FutureFireStore()),
4737
const SizedBox(height: 10),
48-
ElevatedButton(
49-
child: const Text(
50-
'Clean DB',
51-
style: TextStyle(fontSize: 20),
52-
),
53-
onPressed: () {
54-
cleanDB();
55-
},
56-
),
38+
testSectionButton(
39+
context: context,
40+
name: 'Stream Firestore',
41+
widget: const StreamFireStore()),
42+
const SizedBox(height: 10),
43+
cleanDBbutton(),
44+
const SizedBox(height: 10),
45+
testSectionButton(
46+
context: context,
47+
name: 'Old Json Caching Example',
48+
widget: const JsonPage()),
5749
const SizedBox(height: 50),
58-
Card(
59-
child: ListTile(
60-
leading: const Icon(Icons.person),
61-
title: Text(user.displayName.toString()),
62-
subtitle: Text(user.email.toString()),
63-
trailing: IconButton(
64-
onPressed: () {
65-
FirebaseService().signOutFromGoogle();
66-
Navigator.push(context,
67-
MaterialPageRoute(builder: (_) => const LoginPage()));
68-
},
69-
icon: const Icon(Icons.logout)),
70-
),
71-
elevation: 8,
72-
),
50+
userProfileCard(context: context, user: user)
7351
],
7452
)),
7553
);
7654
}
7755
}
56+
57+
Widget testSectionButton(
58+
{required BuildContext context,
59+
required String name,
60+
required Widget widget}) {
61+
return ElevatedButton(
62+
child: Text(
63+
name,
64+
style: const TextStyle(fontSize: 20),
65+
),
66+
onPressed: () {
67+
Navigator.push(
68+
context,
69+
MaterialPageRoute(builder: (context) => widget),
70+
);
71+
},
72+
);
73+
}
74+
75+
Widget cleanDBbutton() {
76+
return ElevatedButton(
77+
child: const Text(
78+
'Clean DB',
79+
style: TextStyle(fontSize: 20),
80+
),
81+
onPressed: () {
82+
cleanDB();
83+
},
84+
);
85+
}
86+
87+
Widget userProfileCard({required BuildContext context, required User user}) {
88+
return Card(
89+
child: ListTile(
90+
leading: const Icon(Icons.person),
91+
title: Text(user.displayName.toString()),
92+
subtitle: Text(user.email.toString()),
93+
trailing: IconButton(
94+
onPressed: () {
95+
FirebaseService().signOutFromGoogle();
96+
Navigator.push(
97+
context, MaterialPageRoute(builder: (_) => const LoginPage()));
98+
},
99+
icon: const Icon(Icons.logout)),
100+
),
101+
elevation: 8,
102+
);
103+
}

lib/screen/login_page.dart

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -10,45 +10,46 @@ class LoginPage extends StatefulWidget {
1010
}
1111

1212
class _LoginPageState extends State<LoginPage> {
13-
void click() async {
14-
await FirebaseService().signInwithGoogle().then((user) {
15-
Navigator.push(
16-
context, MaterialPageRoute(builder: (_) => HomePage(user)));
17-
});
18-
}
19-
20-
Widget googleLoginButton() {
21-
return OutlinedButton(
22-
style: OutlinedButton.styleFrom(
23-
shape: RoundedRectangleBorder(
24-
borderRadius: BorderRadius.circular(45))),
25-
onPressed: click,
26-
child: Padding(
27-
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
28-
child: Row(
29-
mainAxisSize: MainAxisSize.min,
30-
mainAxisAlignment: MainAxisAlignment.center,
31-
children: const [
32-
Image(image: AssetImage('images/google_logo.png'), height: 35),
33-
Padding(
34-
padding: EdgeInsets.only(left: 10),
35-
child: Text('Sign in with Google',
36-
style: TextStyle(color: Colors.grey, fontSize: 25)))
37-
],
38-
),
39-
));
40-
}
41-
4213
@override
4314
Widget build(BuildContext context) {
4415
// FirebaseService().signOutFromGoogle();
4516
return Scaffold(
4617
appBar: AppBar(
18+
automaticallyImplyLeading: false,
4719
title: const Text('Login Screen'),
4820
),
4921
body: Center(
50-
child: googleLoginButton(),
22+
child: googleLoginButton(context: context),
5123
),
5224
);
5325
}
5426
}
27+
28+
Widget googleLoginButton({required BuildContext context}) {
29+
void click() async {
30+
await FirebaseService().signInwithGoogle().then((user) {
31+
Navigator.push(
32+
context, MaterialPageRoute(builder: (_) => HomePage(user)));
33+
});
34+
}
35+
36+
return OutlinedButton(
37+
style: OutlinedButton.styleFrom(
38+
shape:
39+
RoundedRectangleBorder(borderRadius: BorderRadius.circular(45))),
40+
onPressed: click,
41+
child: Padding(
42+
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
43+
child: Row(
44+
mainAxisSize: MainAxisSize.min,
45+
mainAxisAlignment: MainAxisAlignment.center,
46+
children: const [
47+
Image(image: AssetImage('images/google_logo.png'), height: 35),
48+
Padding(
49+
padding: EdgeInsets.only(left: 10),
50+
child: Text('Sign in with Google',
51+
style: TextStyle(color: Colors.grey, fontSize: 25)))
52+
],
53+
),
54+
));
55+
}

0 commit comments

Comments
 (0)