Skip to content

Commit

Permalink
implemented upload page backend and a lot of refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
SP-XD committed Dec 29, 2021
1 parent 0782dc1 commit abf1742
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 74 deletions.
58 changes: 29 additions & 29 deletions go_green/lib/gogreen_home.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:go_green/database.dart';
import 'package:go_green/provider/database.dart';
import 'package:go_green/pages/welcome_page.dart';
import 'package:provider/provider.dart';
import 'nav_bar.dart';

class GoGreenHome extends StatefulWidget {
Expand All @@ -15,33 +16,32 @@ class _GoGreenHomeState extends State<GoGreenHome> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if( snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
else if (snapshot.hasData){
final user = snapshot.data as User;
DataBase.userUid=user.uid ;

debugPrint('snapshot.hasData = $snapshot.hasData');
return const NavBar();
}
else if(snapshot.hasError){
return const Center(
child: Text(
'Something Went Wrong',
style: TextStyle(
color: Colors.red,
)
),
);
}
return const WelcomePage();
},
),
);
}
body: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if( snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
else if (snapshot.hasData){
final user = snapshot.data as User;
DataBase.userUid=user.uid ;

debugPrint('snapshot.hasData = $snapshot.hasData');
return const NavBar();
}
else if(snapshot.hasError){
return const Center(
child: Text(
'Something Went Wrong',
style: TextStyle(
color: Colors.red,
)
),
);
}
return const WelcomePage();
},
),
); }
}

5 changes: 4 additions & 1 deletion go_green/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import 'package:go_green/provider/google_sign_in.dart';
import 'package:go_green/utils/routes.dart';
import 'package:provider/provider.dart';
import 'pages/welcome_page.dart';
import 'package:go_green/provider/database.dart';

void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const GoGreen());
runApp(ChangeNotifierProvider(
create: (context) => DataBase(),
child:const GoGreen()));
}

class GoGreen extends StatelessWidget{
Expand Down
53 changes: 26 additions & 27 deletions go_green/lib/pages/task_page.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:go_green/database.dart';
import 'package:go_green/provider/database.dart';
import 'package:go_green/pages/upload_page.dart';
import 'package:provider/provider.dart';

class TaskPage extends StatefulWidget {
const TaskPage({Key? key}) : super(key: key);
Expand All @@ -11,11 +12,11 @@ class TaskPage extends StatefulWidget {

class _TaskPageState extends State<TaskPage> {

int totalScore=0;
Map<String, bool> taskList={};
//int totalScore=0;
//Map<String, bool> taskList={};


Widget _taskScoreBoard({required int score}){
Widget _taskScoreBoard(){

return Row(
mainAxisAlignment: MainAxisAlignment.center,
Expand Down Expand Up @@ -56,16 +57,16 @@ class _TaskPageState extends State<TaskPage> {
),
borderRadius: BorderRadius.circular(10)
),
child: Text(
'$score',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w900,
color: Colors.grey.shade800,
),
child: Text(
Provider.of<DataBase>(context).readTotalScore().toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w900,
color: Colors.grey.shade800,
),
)
),
),
],
)
],
Expand Down Expand Up @@ -100,7 +101,7 @@ class _TaskPageState extends State<TaskPage> {
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: taskList.keys.map((String taskName){
children: DataBase.taskList.keys.map((String taskName){
return CheckboxListTile(
title: Text(taskName, style: TextStyle(
fontSize: 14,
Expand All @@ -110,17 +111,14 @@ class _TaskPageState extends State<TaskPage> {
activeColor: Colors.grey.shade800,
controlAffinity: ListTileControlAffinity.leading,
visualDensity: const VisualDensity(horizontal: 0, vertical: -1),
value: taskList[taskName],
value: DataBase.taskList[taskName],
onChanged: (bool? value){
setState(() {
taskList[taskName]=value!;
if(value) {
totalScore+=10;
if(value!) {
Navigator.push(context, MaterialPageRoute(builder: (context)=> UploadPage(taskName: taskName)));
} else {
totalScore-=10;
Provider.of<DataBase>(context, listen: false).updateTask(taskName: taskName, status: value, updateScoreBy: -10);
}
DataBase.updateTaskStatus(taskName: taskName, status: value, score: totalScore);
});
},
);
Expand All @@ -140,17 +138,18 @@ class _TaskPageState extends State<TaskPage> {
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height*0.9,
child: FutureBuilder<Map<String, dynamic>>(
future: DataBase.readTasksList(),
future: DataBase().readTasksList(),
builder: (context, snapshot) {
if(snapshot.hasData){
if(taskList.isEmpty){

if(DataBase.taskList.isEmpty){
final userData= snapshot.data;
final fulltaskList= Map<String, bool>.from(userData?['tasklist']);
totalScore=userData!['score'];
DataBase.totalScore=userData!['score'];
//number of tasks
int c=0;
//shortlisting the number of tasks
fulltaskList.forEach((key, value) { if(value==false && c<3 ){ taskList[key]=value; c++; }});
fulltaskList.forEach((key, value) { if(value==false && c<3 ){ DataBase.taskList[key]=value; c++; }});

}

Expand All @@ -162,7 +161,7 @@ class _TaskPageState extends State<TaskPage> {
SizedBox(
height: MediaQuery.of(context).size.height*0.1,
),
Flexible(child: _taskScoreBoard(score: totalScore)),
Flexible(child: _taskScoreBoard()),
SizedBox(
height: MediaQuery.of(context).size.height*0.01,
),
Expand All @@ -174,7 +173,7 @@ class _TaskPageState extends State<TaskPage> {
return SafeArea(child: Center(
child: Text(
'Error ${snapshot.error}',

)));
}
else{
Expand All @@ -183,7 +182,7 @@ class _TaskPageState extends State<TaskPage> {
color: Colors.green,
),));
}

}
),
)),
Expand Down
72 changes: 66 additions & 6 deletions go_green/lib/pages/upload_page.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import 'dart:io';

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_green/provider/database.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:provider/provider.dart';

class UploadPage extends StatefulWidget {
final String taskName;
Expand All @@ -15,7 +19,8 @@ class UploadPage extends StatefulWidget {
class _UploadPageState extends State<UploadPage> {

File? imageOrVideo;

UploadTask? task;

Future pickImage(ImageSource source)async{
try {
final image= await ImagePicker().pickImage(source: source);
Expand All @@ -39,6 +44,51 @@ class _UploadPageState extends State<UploadPage> {
}
}

Future uploadImageVideo() async {
if(imageOrVideo==null) return;

final fileName = basename(imageOrVideo!.path);
final destination = 'UserUploads/${DataBase.userUid}/$fileName';

task= DataBase().uploadFile(destination, imageOrVideo!);

setState(() {
});

}
Widget buildUploadStatus(BuildContext context,UploadTask task)=> StreamBuilder<TaskSnapshot>(
stream: task.snapshotEvents,
builder: (context, snapshot){
if(snapshot.hasData){
final snap = snapshot.data!;
final progress= snap.bytesTransferred/snap.totalBytes;
final percentage = (progress*100).toStringAsFixed(2);
debugPrint('percentage : $percentage');
if(progress==1){
debugPrint('image or video file uploaded');
debugPrint('total score in uploadpage: ${DataBase.totalScore}');
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) async {
debugPrint('timestamp: $timeStamp');
Provider.of<DataBase>(context, listen: false).updateTask(taskName: widget.taskName, status: true, updateScoreBy: 10);
await Future.delayed(const Duration(seconds: 2),(){});
Navigator.pop(context);
});
}

return Text(
'Uploaded $percentage %',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
),
);
}
else{
return const Text('starting upload...', style: TextStyle(fontWeight: FontWeight.bold),);
}

});

@override
Widget build(BuildContext context) {
return Scaffold(
Expand Down Expand Up @@ -110,8 +160,9 @@ class _UploadPageState extends State<UploadPage> {
),
labelPadding: const EdgeInsets.symmetric(vertical: 5, horizontal: 15),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
onPressed: (){
pickImage(ImageSource.camera);
onPressed: ()async{
await pickImage(ImageSource.camera);
uploadImageVideo();
}
),
const SizedBox(
Expand All @@ -127,8 +178,9 @@ class _UploadPageState extends State<UploadPage> {
),
labelPadding: const EdgeInsets.symmetric(vertical: 5, horizontal: 20),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
onPressed: (){
pickVideo(ImageSource.camera);
onPressed: ()async{
await pickVideo(ImageSource.camera);
uploadImageVideo();
}
),
const SizedBox(
Expand All @@ -144,7 +196,15 @@ class _UploadPageState extends State<UploadPage> {
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
onPressed: (){
Navigator.of(context).pop();
})
}),
const SizedBox(height: 20,),
task != null ? buildUploadStatus(context, task!) : const Text(
'File not selected!',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold
)
),
],
)),
],
Expand Down
Loading

0 comments on commit abf1742

Please sign in to comment.