Skip to content

Commit

Permalink
formatting the code, adding files in controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
Amartya-Mahato committed Nov 22, 2022
1 parent 95c27fc commit 06dfd93
Show file tree
Hide file tree
Showing 13 changed files with 495 additions and 582 deletions.
213 changes: 213 additions & 0 deletions lib/controllers/database.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:news_app/controllers/navigation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Database {
static Future<int> updateLikes(int prevLike, String id) async {
int likes = prevLike;

DocumentReference<Map<String, dynamic>> doc =
FirebaseFirestore.instance.collection('articals').doc(id);

var snapshot = await doc.get();
List? snapList = snapshot.data()!['liked'];
snapList ??= [];
var pref = await SharedPreferences.getInstance();

if (!snapList.contains(pref.getString('email')) || likes <= 0) {
snapList.add(pref.getString('email'));
await doc.update({'likes': likes + 1, 'liked': snapList});
likes = likes + 1;
} else {
snapList.remove(pref.getString('email'));
await doc.update({'likes': likes - 1, 'liked': snapList});
likes = likes - 1;
}
return likes;
}

static Future<List<QueryDocumentSnapshot<Map<String, dynamic>>>>
deleteBookmark(
String email,
String id,
List<QueryDocumentSnapshot<Map<String, dynamic>>> cartItems,
int index) async {
var doc = FirebaseFirestore.instance.collection('user').doc(email);

List<dynamic> list;
var instance = await doc.get();
list = instance.data()!['bookmark'];
list.remove(cartItems[index].id);
cartItems.remove(cartItems[index]);
await doc.update({'bookmark': list});

return cartItems;
}

static void appyEdits(
bool isUploading,
BuildContext context,
QueryDocumentSnapshot<Map<String, dynamic>> snapshot,
String image,
int amount,
String discription,
String title,
String upi,
int likes,
String writer,
List liked,
String email) {
if (image != snapshot.data()['image']) {
FirebaseStorage.instance.refFromURL(snapshot.data()['image']).delete();
}
FirebaseFirestore.instance.collection('articals').doc(snapshot.id).set({
'amount': amount,
'discription': discription,
'image': image,
'title': title,
'upi': upi,
'likes': likes,
'writer': writer,
'liked': liked,
'email': email,
});

if (!isUploading) {
Navigator.pop(context);
}
}

static void deleteArtical(
BuildContext context,
QueryDocumentSnapshot<Map<String, dynamic>> snapshot,
String email) async {
// Remove the artical
FirebaseFirestore.instance.collection('articals').doc(snapshot.id).delete();

//Remove from writer account
var doc = FirebaseFirestore.instance.collection('user').doc(email);
var snap = await doc.get();
List list = snap.data()!['articals'];
list.remove(snapshot.id);
await doc.update({'articals': list});

// Remove from reader's account
var query = FirebaseFirestore.instance
.collection('user')
.where('bookmark', arrayContains: snapshot.id);
var querySnapshot = await query.get();
List<QueryDocumentSnapshot<Map<String, dynamic>>> queryList =
querySnapshot.docs;
for (int i = 0; i < queryList.length; i++) {
List cartList = queryList[i].data()['bookmark'];
cartList.remove(snapshot.id);
await FirebaseFirestore.instance
.collection('user')
.doc(queryList[i].id)
.update({'bookmark': cartList});
}

//Remove the image
FirebaseStorage.instance.refFromURL(snapshot.data()['image']).delete();

Navigator.pop(context);
}

static void addToBookmark(BuildContext context, String email, String id) {
DocumentReference<Map<String, dynamic>> doc =
FirebaseFirestore.instance.collection('user').doc(email);

doc.get().then((value) {
List list = value.data()!['bookmark'];
if (!list.contains(id)) {
list.add(id);
doc.update({'bookmark': list});

ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.black,
content: Text("Artical added in your cart")));
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.black,
content: Text("Artical is already present in you cart")));
}
});
}

static void registerAccount(BuildContext context, String email, String pass,
String upi, String name) {
FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: pass)
.then((value) {
SharedPreferences.getInstance().then((pref) {
pref.setBool('login', true);
pref.setString('email', email);
pref.setString('name', name);
pref.setString('upi', upi);

FirebaseFirestore.instance.collection('user').doc(email).set({
'bookmark': [],
'articals': [],
'name': name,
'upi': upi
}).then((_) {
Navigation.toReaderHomeAndRemovePrevPages(context);
});
});
}).onError((error, stackTrace) {});
}

static void loginAccount(BuildContext context, String email, String pass) {
FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: pass)
.then((value) async {
SharedPreferences.getInstance().then((pref) {
pref.setBool('login', true);
pref.setString('email', email);

FirebaseFirestore.instance
.collection('user')
.doc(email)
.get()
.then((documentsnapshot) {
pref.setString('name', documentsnapshot['name']);
pref.setString('upi', documentsnapshot['upi']);

Navigation.toReaderHomeAndRemovePrevPages(context);
});
});
}).onError((error, stackTrace) {});
}

static void createArtical(
List<Object?> articalFields, String upi, String name, String email) {
var document = FirebaseFirestore.instance.collection('articals').doc();
document.set({
'amount': articalFields[2] as int,
'discription': articalFields[3] as String,
'image': articalFields[0] as String,
'title': articalFields[1] as String,
'upi': upi,
'writer': name,
'likes': 0,
'liked': [],
'email': email,
});

FirebaseFirestore.instance
.collection('user')
.doc(email)
.get()
.then((value) async {
Map<String, dynamic> mpp = value.data()!;
mpp['articals'].add(document.id);
await FirebaseFirestore.instance
.collection('user')
.doc(email)
.update({'articals': mpp['articals']});
});
}
}
85 changes: 85 additions & 0 deletions lib/controllers/navigation.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../pages/artical_page.dart';
import '../pages/bookmark_page.dart';
import '../pages/edit_page.dart';
import '../pages/reader_home.dart';
import '../pages/register_account.dart';
import '../pages/user_login.dart';
import '../pages/write_artical.dart';
import '../pages/writer_home.dart';

class Navigation {
static void toLoginPage(BuildContext context) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: ((context) => const UserLogin())),
(route) => false);
}

static void toLogout(BuildContext context) {
FirebaseAuth.instance.signOut();
SharedPreferences.getInstance().then((value) {
value.remove('name');
value.remove('email');
value.remove('login');
value.clear();

Navigation.toLoginPage(context);
});
}

static void toRegisterPage(BuildContext context) {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const RegisterAccount()));
}

static void toArticalPage(BuildContext context,
List<QueryDocumentSnapshot<Map<String, dynamic>>> cartItems, int index) {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => ArticalPage(snapshot: cartItems[index]))));
}

static void toBookmarkPage(BuildContext context, String email) {
Navigator.push(context,
MaterialPageRoute(builder: ((context) => BookmarkPage(email: email))));
}

static void toEditArticalPage(BuildContext context,
QueryDocumentSnapshot<Map<String, dynamic>> snapshot) {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => EditPage(snapshot: snapshot))));
}

static Future<List<Object>?> toWriteArticalPage(
BuildContext context, String name, String email) async {
return await Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => WriteArtical(
name: name,
email: email,
))));
}

static void toReaderHomeAndRemovePrevPages(BuildContext context) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => const ReaderHome()),
(route) => false);
}

static void toWriterHomeAndRemovePrevPages(BuildContext context) {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: ((context) => const WriterHome())),
(route) => false);
}
}
79 changes: 4 additions & 75 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:news_app/pages/login_page.dart';
import 'package:news_app/pages/reader_home.dart';
import 'package:news_app/pages/writer_home.dart';
import 'package:news_app/pages/user_login.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'firebase_options.dart';
Expand All @@ -15,85 +14,15 @@ void main() async {

SharedPreferences prefs = await SharedPreferences.getInstance();
bool? login = prefs.getBool('login');
bool? isWriter = prefs.getBool('isWriter');

runApp(MaterialApp(
title: 'News App',
routes: {
'/login': (context) => const LoginPage(),
'/reder_home': (context) => const ReaderHome(),
'/writer_home': (context) => const WriterHome(),
},
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.black,
),
home: login == null || isWriter == null
? const LoginPage()
: isWriter
? const WriterHome()
: const ReaderHome(),
home: login == null
? const UserLogin()
: const ReaderHome(),
));
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Loading

0 comments on commit 06dfd93

Please sign in to comment.