repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/Visitor-Tracker/lib | mirrored_repositories/Visitor-Tracker/lib/screens/signup.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class SignUpScreen extends StatefulWidget {
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"SIGN UP",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/signup.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _emailController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.email_outlined,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _passwordController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Password",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.lock,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
obscureText: true,
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("SIGN UP"),
onPressed: () {
_signUp();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
],
),
),
],
),
),
),
);
}
void _signUp() async {
final String emailTXT = _emailController.text.trim();
final String passwordTXT = _passwordController.text;
if (emailTXT.isNotEmpty && passwordTXT.isNotEmpty) {
_auth
.createUserWithEmailAndPassword(
email: emailTXT, password: passwordTXT)
.then((user) {
//Successful signup
_db.collection("users").doc(user.user.uid).set({
"email": emailTXT,
"last_seen": DateTime.now(),
"signup_method": user.user.providerData[0].providerId
});
//Show success alert-dialog
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Sign Up successful, you are now logged In!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}).catchError((e) {
//Show Errors if any
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
});
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please provide Email and Password!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/a_qr_result.dart | import 'package:flutter/material.dart';
class QRCodeResult extends StatelessWidget {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Center(
child: Text(
"QR CODE RESULT",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
)),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/admin_signup.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class AdminSignUp extends StatefulWidget {
@override
_AdminSignUpState createState() => _AdminSignUpState();
}
class _AdminSignUpState extends State<AdminSignUp> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"ADMIN SIGN-UP",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/signup.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _emailController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.email_outlined,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _passwordController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Password",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.lock,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
obscureText: true,
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("SIGN UP"),
onPressed: () {
_signUp();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
],
),
),
],
),
),
),
);
}
void _signUp() async {
final String emailTXT = _emailController.text.trim();
final String passwordTXT = _passwordController.text;
if (emailTXT.isNotEmpty && passwordTXT.isNotEmpty) {
_auth
.createUserWithEmailAndPassword(
email: emailTXT, password: passwordTXT)
.then((user) {
//Successful signup
_db.collection("admin_users").doc(user.user.uid).set({
"email": emailTXT,
"last_seen": DateTime.now(),
"signup_method": user.user.providerData[0].providerId
});
//Show success alert-dialog
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Sign Up successful, you are now logged In!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}).catchError((e) {
//Show Errors if any
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
});
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please provide Email and Password!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/admin_login.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AdminLogin extends StatefulWidget {
@override
_AdminLoginState createState() => _AdminLoginState();
}
class _AdminLoginState extends State<AdminLogin> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseFirestore _db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"WELCOME ADMIN",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/login.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _emailController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.email_outlined,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _passwordController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Password",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.lock,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
obscureText: true,
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("LOGIN"),
onPressed: () {
_signIn();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
SizedBox(
height: 25,
),
TextButton(
child: Text(
"New here? Sign Up using Email",
style: TextStyle(
fontSize: 18,
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.pushNamed(context, "/adminsignup");
},
),
SizedBox(
height: 13,
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FaIcon(
FontAwesomeIcons.google,
color: Colors.red,
size: 22,
),
SizedBox(
width: 7,
),
TextButton(
child: Text(
'Login using Google',
style: TextStyle(
fontSize: 20,
color: Colors.red,
),
),
onPressed: () {
_signInUsingGoogle();
},
),
],
),
onTap: () {},
),
],
),
),
],
),
),
),
);
}
void _signIn() async {
String email = _emailController.text.trim();
String password = _passwordController.text;
if (email.isNotEmpty && password.isNotEmpty) {
_auth
.signInWithEmailAndPassword(email: email, password: password)
.then((user) {
_db.collection("admin_users").doc(user.user.uid).set({
"email": email,
"last_seen": DateTime.now(),
"signup_method": user.user.providerData[0].providerId
});
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Sign In Success"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}).catchError((e) {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
});
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please provide Email and Password!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
_emailController.text = "";
_passwordController.text = "";
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
void _signInUsingGoogle() async {
try {
// Trigger the authentication flow
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
// Create a new credential
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Once signed in, return the UserCredential
final User user = (await _auth.signInWithCredential(credential)).user;
print("Signed In " + user.displayName);
if (user != null) {
//Successful signup
_db.collection("admin_users").doc(user.uid).set({
"displayName": user.displayName,
"email": user.email,
"last_seen": DateTime.now(),
"signup_method": user.providerData[0].providerId
});
}
} catch (e) {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/admin_option.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AdminOption extends StatefulWidget {
@override
_AdminOptionState createState() => _AdminOptionState();
}
class _AdminOptionState extends State<AdminOption> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"WELCOME ADMIN",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/admin.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, "/qrcodescanner");
},
child: Center(
child: Text(
"Scan QR Code",
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xffC6C7C4).withOpacity(0.5),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, "/uploadeddata");
},
child: Center(
child: Text(
"View uploaded details",
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xffC6C7C4).withOpacity(0.5),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
onPressed: () async {
await _auth.signOut();
_googleSignIn.signOut();
Navigator.of(context).pop();
},
child: Center(
child: Text(
"LOGOUT",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xff6C63FF),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/visitor_detail.dart | import 'package:flutter/material.dart';
class VisitorDetail extends StatefulWidget {
final String userDetail;
final String uploadedTime;
const VisitorDetail({
Key key,
this.userDetail,
this.uploadedTime,
}) : super(key: key);
@override
VisitorDetailState createState() => VisitorDetailState();
}
class VisitorDetailState extends State<VisitorDetail> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"VISITOR DETAIL",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 40,
),
Container(
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
border: Border.all(color: Color(0xff6C63FF)),
),
child: Column(
children: [
Container(
padding: EdgeInsets.all(5),
child: Text(
"Details",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
height: 5,
),
Container(
child: Text(
"${widget.userDetail}",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24,
color: Colors.black,
),
),
),
SizedBox(
height: 20,
),
Container(
padding: EdgeInsets.all(5),
child: Text(
"Uploaded Time",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
height: 5,
),
Container(
padding: EdgeInsets.all(5),
child: Text(
"${widget.uploadedTime}",
style: TextStyle(
fontSize: 24,
color: Colors.black,
),
),
),
],
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/a_upload.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class UploadData extends StatefulWidget {
final String text;
const UploadData({Key key, this.text}) : super(key: key);
@override
_UploadDataState createState() => _UploadDataState();
}
class _UploadDataState extends State<UploadData> {
final FirebaseFirestore _db = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
User user;
@override
void initState() {
getUid();
super.initState();
}
void getUid() {
User u = _auth.currentUser;
setState(() {
user = u;
});
}
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"UPLOAD DATA",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 40,
),
Container(
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
border: Border.all(color: Colors.red),
),
child: Text(
"${widget.text}",
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
SizedBox(
height: 30,
),
Container(
padding: EdgeInsets.all(15),
child: Text(
"Upon pressing UPLOAD button, the above data would be uploaded.",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.red[600],
),
),
),
SizedBox(
height: 40,
),
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
child: Text("UPLOAD"),
onPressed: () async {
String uploaddata = widget.text.trim();
_db
.collection("users")
.doc(user.uid)
.collection("visitor_details")
.add({
"visitor_details": uploaddata,
"uploaded_time": DateTime.now()
});
_showDialog();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 20,
),
padding: EdgeInsets.all(8.0),
),
),
),
],
),
),
),
);
}
void _showDialog() {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Visitor record uploaded successfully"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/a_qr_scan.dart | import 'package:barcode_scan_fix/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:visitor_tracker/screens/administrator/a_upload.dart';
import 'dart:async';
import 'package:visitor_tracker/screens/administrator/qr.dart';
class QRCodeScanner extends StatefulWidget {
@override
_QRCodeScannerState createState() => _QRCodeScannerState();
}
class _QRCodeScannerState extends State<QRCodeScanner> {
String qrCodeResult = "Visitor details not yet Scanned";
int correctQRDecoded = 0;
Future _scanQR() async {
try {
String qrResult = await BarcodeScanner.scan();
setState(() {
qrCodeResult = qrResult;
correctQRDecoded = 1;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
qrCodeResult = "Camera permission was denied";
});
} else {
setState(() {
qrCodeResult = "Unknown Error $ex";
});
}
} on FormatException {
setState(() {
qrCodeResult = "You pressed the back button before scanning anything";
});
} catch (ex) {
setState(() {
qrCodeResult = "Unknown Error $ex";
});
}
}
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
_navigateScannedQR(BuildContext context) async {
QR qr = new QR(qrCodeResult);
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UploadData(
text: qr.text,
)));
print(result);
}
Widget uploadButton = new Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
child: Text("UPLOAD SCANNED DETAILS"),
onPressed: () async {
_navigateScannedQR(context);
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xffF50057),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 20,
),
padding: EdgeInsets.all(8.0),
),
),
);
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"QR CODE SCANNER",
style: TextStyle(
color: Color(0xff6C63FF),
fontSize: 30.0,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
SizedBox(
height: 70.0,
),
Container(
padding: EdgeInsets.all(15),
decoration: BoxDecoration(
border: Border.all(color: Colors.red),
),
child: Text(
qrCodeResult,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
),
textAlign: TextAlign.center,
),
),
SizedBox(
height: 70.0,
),
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
child: Text("OPEN SCANNER"),
onPressed: _scanQR,
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 20,
),
padding: EdgeInsets.all(8.0),
),
),
),
SizedBox(
height: 30,
),
correctQRDecoded == 0 ? Container() : uploadButton
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/vd.dart | class VD {
final String userDetail;
final String uploadedTime;
VD(this.userDetail, this.uploadedTime);
} | 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/admin_home.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:visitor_tracker/screens/administrator/admin_login.dart';
import 'package:visitor_tracker/screens/administrator/admin_option.dart';
class AdminHome extends StatefulWidget {
@override
_AdminHomeState createState() => _AdminHomeState();
}
class _AdminHomeState extends State<AdminHome> {
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: _auth.authStateChanges(),
builder: (ctx, AsyncSnapshot<User> snapshot) {
if (snapshot.hasData) {
User user = snapshot.data;
if (user != null) {
return AdminOption();
} else {
return AdminLogin();
}
}
return AdminLogin();
},
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/qr.dart | class QR {
final String text;
QR(this.text);
} | 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/administrator/a_uploaded_data.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';
import 'package:visitor_tracker/screens/administrator/vd.dart';
import 'package:visitor_tracker/screens/administrator/visitor_detail.dart';
class UploadedData extends StatefulWidget {
@override
_UploadedDataState createState() => _UploadedDataState();
}
class _UploadedDataState extends State<UploadedData> {
final FirebaseFirestore _db = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
User user;
@override
void initState() {
getUid();
super.initState();
}
void getUid() {
User u = _auth.currentUser;
setState(() {
user = u;
});
}
String formatTimestamp(Timestamp timestamp) {
var format =
new DateFormat.yMMMMd('en_US').add_jm(); // 'hh:mm' for hour & min
return format.format(timestamp.toDate());
}
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Container(
child: StreamBuilder(
stream: _db
.collection("users")
.doc(user.uid)
.collection("visitor_details")
.orderBy("uploaded_time", descending: true)
.snapshots(),
builder: (ctx, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.docs.isNotEmpty) {
return ListView(
children: snapshot.data.docs.map((snap) {
return Padding(
padding:
const EdgeInsets.fromLTRB(8.0, 4.0, 8.0, 0.0),
child: Card(
child: ListTile(
title: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Flexible(
child: Text(
snap["visitor_details"].substring(0, 17),
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
],
),
),
subtitle: Padding(
padding: const EdgeInsets.fromLTRB(
8.0, 4.0, 4.0, 4.0),
child: Row(
children: [
Flexible(
child: Text(
formatTimestamp(snap["uploaded_time"])
.toString(),
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
color: Colors.white,
),
),
),
],
),
),
trailing: Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
icon: Icon(
Icons.delete_rounded,
color: Colors.white,
size: 30,
),
onPressed: () {
_db
.collection("users")
.doc(user.uid)
.collection("visitor_details")
.doc(snap.id)
.delete();
_showDialog();
},
),
),
onTap: () {
VD vd = new VD(
snap["visitor_details"],
formatTimestamp(snap["uploaded_time"])
.toString());
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VisitorDetail(
userDetail: vd.userDetail,
uploadedTime: vd.uploadedTime,
)));
},
contentPadding: EdgeInsets.all(7.0),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
color: Color(0xff6C63FF),
elevation: 10,
),
);
}).toList(),
);
} else {
return Container(
child: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"UPLOADED DATA",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 20,
),
Image(
image: AssetImage("assets/images/no_data.png"),
),
SizedBox(
height: 30,
),
Text(
"No data uploaded",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.red[500],
),
),
],
),
),
),
);
}
}
return Container(
child: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"UPLOADED DATA",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 20,
),
Image(
image: AssetImage("assets/images/no_data.png"),
),
SizedBox(
height: 30,
),
Text(
"No data uploaded",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.red[500],
),
),
],
),
),
),
);
},
),
),
),
),
);
}
void _showDialog() {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Visitor record deleted successfully"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/visitor_home.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:visitor_tracker/screens/visitor/visitor_login.dart';
import 'package:visitor_tracker/screens/visitor/visitor_option.dart';
class VisitorHome extends StatefulWidget {
@override
_VisitorHomeState createState() => _VisitorHomeState();
}
class _VisitorHomeState extends State<VisitorHome> {
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream: _auth.authStateChanges(),
builder: (ctx, AsyncSnapshot<User> snapshot) {
if (snapshot.hasData) {
User user = snapshot.data;
if (user != null) {
return VisitorOption();
} else {
return VisitorLogin();
}
}
return VisitorLogin();
},
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/v_detail_entry.dart | import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:visitor_tracker/screens/visitor/models/visitor_model.dart';
import 'package:visitor_tracker/screens/visitor/v_detail_update.dart';
class VisitorDetailEntry extends StatefulWidget {
@override
_VisitorDetailEntryState createState() => _VisitorDetailEntryState();
}
class _VisitorDetailEntryState extends State<VisitorDetailEntry> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"ENTER DETAILS",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 15,
),
SizedBox(
height: 120,
child: _buildListView(),
),
VisitorDetailUpdate(),
],
),
),
),
);
}
}
Widget _buildListView() {
// ignore: deprecated_member_use
return WatchBoxBuilder(
box: Hive.box('visitor'),
builder: (context, visitorBox) {
return ListView.builder(
itemCount: visitorBox.length,
itemBuilder: (context, index) {
final visitor = visitorBox.getAt(index) as Visitor;
print(visitor.address);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: ListTile(
title: Text(
visitor.name,
style: TextStyle(
fontSize: 20,
color: Colors.black,
),
),
subtitle: Text(
visitor.number.toString(),
style: TextStyle(
fontSize: 16,
color: Colors.black,
),
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
visitorBox.deleteAt(index);
},
),
),
);
},
);
},
);
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/visitor_signup.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class VisitorSignUp extends StatefulWidget {
@override
_VisitorSignUpState createState() => _VisitorSignUpState();
}
class _VisitorSignUpState extends State<VisitorSignUp> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"VISITOR SIGN-UP",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/signup.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _emailController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.email_outlined,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _passwordController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Password",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.lock,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
obscureText: true,
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("SIGN UP"),
onPressed: () {
_signUp();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
],
),
),
],
),
),
),
);
}
void _signUp() async {
final String emailTXT = _emailController.text.trim();
final String passwordTXT = _passwordController.text;
if (emailTXT.isNotEmpty && passwordTXT.isNotEmpty) {
_auth
.createUserWithEmailAndPassword(
email: emailTXT, password: passwordTXT)
.then((user) {
//Successful signup
_db.collection("visitor_users").doc(user.user.uid).set({
"email": emailTXT,
"last_seen": DateTime.now(),
"signup_method": user.user.providerData[0].providerId
});
//Show success alert-dialog
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Sign Up successful, you are now logged In!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}).catchError((e) {
//Show Errors if any
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
});
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please provide Email and Password!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/v_qr_gen.dart | import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:qr_flutter/qr_flutter.dart';
class QRCodeGenerator extends StatefulWidget {
@override
_QRCodeGeneratorState createState() => _QRCodeGeneratorState();
}
class _QRCodeGeneratorState extends State<QRCodeGenerator> {
String qrData = "";
@override
void initState() {
final visitorBox = Hive.box('visitor');
final visitor = visitorBox.getAt(0);
qrData = "" + visitor.name + " & " + visitor.number + " & " + visitor.address;
print(qrData);
super.initState();
}
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 25,
),
Text(
"GENERATED QR CODE",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 55,
),
QrImage(
data: qrData,
version: QrVersions.auto,
size: 275.0,
errorStateBuilder: (cxt, err) {
return Container(
child: Center(
child: Text(
"No data given to generate QR Code",
textAlign: TextAlign.center,
),
),
);
},
),
],
)),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/visitor_option.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class VisitorOption extends StatefulWidget {
@override
_VisitorOptionState createState() => _VisitorOptionState();
}
class _VisitorOptionState extends State<VisitorOption> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"WELCOME VISITOR",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.5,
child: Image.asset(
"assets/images/visitor.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, "/visitordetails");
},
child: Center(
child: Text(
"Enter personal details",
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xffC6C7C4).withOpacity(0.5),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
SizedBox(
height: 10,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.07,
width: width * 0.8,
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, "/qrcodegenerator");
},
child: Center(
child: Text(
"Generate QR Code",
style: TextStyle(
fontSize: 18,
color: Colors.black,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xffC6C7C4).withOpacity(0.5),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
onPressed: () async {
await _auth.signOut();
_googleSignIn.signOut();
Navigator.of(context).pop();
},
child: Center(
child: Text(
"LOGOUT",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
style: TextButton.styleFrom(
backgroundColor: Color(0xff6C63FF),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
),
),
),
],
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/v_detail_update.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:visitor_tracker/screens/visitor/models/visitor_model.dart';
class VisitorDetailUpdate extends StatefulWidget {
@override
_VisitorDetailUpdateState createState() => _VisitorDetailUpdateState();
}
class _VisitorDetailUpdateState extends State<VisitorDetailUpdate> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _nameControl = TextEditingController();
final TextEditingController _numberControl = TextEditingController();
final TextEditingController _addressControl = TextEditingController();
String _name;
String _number;
String _address;
void addContact(Visitor visitor) {
final visitorBox = Hive.box('visitor');
visitorBox.add(visitor);
}
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _nameControl,
cursorColor: Color(0xff6C63FF),
onSaved: (value) {
_name = value;
},
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Name",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.face,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
cursorColor: Color(0xff6C63FF),
controller: _numberControl,
onSaved: (value) {
_number = value;
},
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Phone Number",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.call,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.phone,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _addressControl,
cursorColor: Color(0xff6C63FF),
onSaved: (value) {
_address = value;
},
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Address",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.home,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
),
),
),
),
SizedBox(
height: 45,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("ADD DETAILS"),
onPressed: () {
_addDetails();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
],
),
);
}
void _addDetails() {
final String nameTXT = _nameControl.text.trim();
final String numberTXT = _numberControl.text.trim();
final String addressTXT = _addressControl.text.trim();
if (nameTXT.isNotEmpty && numberTXT.isNotEmpty && addressTXT.isNotEmpty && numberTXT.length>=10) {
_formKey.currentState.save();
final newVisitor = Visitor(_name, _number, _address);
addContact(newVisitor);
_nameControl.text = "";
_numberControl.text = "";
_addressControl.text = "";
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please fill all the required fields!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/visitor_login.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_sign_in/google_sign_in.dart';
class VisitorLogin extends StatefulWidget {
@override
_VisitorLoginState createState() => _VisitorLoginState();
}
class _VisitorLoginState extends State<VisitorLogin> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseFirestore _db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: height,
width: width,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
),
Text(
"WELCOME VISITOR",
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Color(0xff6C63FF),
),
),
SizedBox(
height: 25,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
width: width * 0.8,
child: Image.asset(
"assets/images/login.png",
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _emailController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Email",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.email_outlined,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: Container(
height: height * 0.07,
width: width * 0.8,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(21),
color: Color(0xffC6C7C4).withOpacity(0.5),
),
child: Center(
child: TextFormField(
controller: _passwordController,
cursorColor: Color(0xff6C63FF),
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Password",
hintStyle: TextStyle(
fontSize: 16,
color: Colors.grey,
),
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0,
),
child: Icon(
Icons.lock,
color: Colors.grey,
size: 25,
),
),
),
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
textInputAction: TextInputAction.next,
obscureText: true,
),
),
),
),
SizedBox(
height: 25,
),
Container(
height: height * 0.08,
width: width * 0.8,
child: ElevatedButton(
child: Text("LOGIN"),
onPressed: () {
_signIn();
},
style: TextButton.styleFrom(
elevation: 0.0,
backgroundColor: Color(0xff6C63FF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(21),
),
textStyle: TextStyle(
fontSize: 24,
),
padding: EdgeInsets.all(8.0),
),
),
),
SizedBox(
height: 15,
),
TextButton(
child: Text(
"New here? Sign Up using Email",
style: TextStyle(
fontSize: 18,
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.pushNamed(context, "/visitorsignup");
},
),
SizedBox(
height: 13,
),
InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FaIcon(
FontAwesomeIcons.google,
color: Colors.red,
size: 22,
),
SizedBox(
width: 7,
),
TextButton(
child: Text(
'Login using Google',
style: TextStyle(
fontSize: 20,
color: Colors.red,
),
),
onPressed: () {
_signInUsingGoogle();
},
),
],
),
onTap: () {},
),
],
),
),
],
),
),
),
);
}
void _signIn() async {
String email = _emailController.text.trim();
String password = _passwordController.text;
if (email.isNotEmpty && password.isNotEmpty) {
_auth
.signInWithEmailAndPassword(email: email, password: password)
.then((user) {
_db.collection("visitor_users").doc(user.user.uid).set({
"email": email,
"last_seen": DateTime.now(),
"signup_method": user.user.providerData[0].providerId
});
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Success"),
content: Text("Sign In Success"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}).catchError((e) {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
});
} else {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("Please provide Email and Password!"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
// ignore: deprecated_member_use
FlatButton(
child: Text(
"OK",
style: TextStyle(
color: Color(0xff6C63FF),
),
),
onPressed: () {
_emailController.text = "";
_passwordController.text = "";
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
void _signInUsingGoogle() async {
try {
// Trigger the authentication flow
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
// Create a new credential
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Once signed in, return the UserCredential
final User user = (await _auth.signInWithCredential(credential)).user;
print("Signed In " + user.displayName);
if (user != null) {
//Successful signup
_db.collection("visitor_users").doc(user.uid).set({
"displayName": user.displayName,
"email": user.email,
"last_seen": DateTime.now(),
"signup_method": user.providerData[0].providerId
});
}
} catch (e) {
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Text("Error"),
content: Text("${e.message}"),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
child: Text(
"Cancel",
style: TextStyle(
color: Colors.red,
),
),
onPressed: () {
Navigator.of(ctx).pop();
},
),
],
);
});
}
}
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens/visitor | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/models/visitor_model.dart | import 'package:hive/hive.dart';
part 'visitor_model.g.dart';
@HiveType(typeId: 0)
class Visitor {
@HiveField(0)
final String name;
@HiveField(1)
final String number;
@HiveField(2)
final String address;
Visitor(this.name, this.number, this.address);
}
| 0 |
mirrored_repositories/Visitor-Tracker/lib/screens/visitor | mirrored_repositories/Visitor-Tracker/lib/screens/visitor/models/visitor_model.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'visitor_model.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class VisitorAdapter extends TypeAdapter<Visitor> {
@override
final int typeId = 0;
@override
Visitor read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Visitor(
fields[0] as String,
fields[1] as String,
fields[2] as String,
);
}
@override
void write(BinaryWriter writer, Visitor obj) {
writer
..writeByte(3)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.number)
..writeByte(2)
..write(obj.address);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is VisitorAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0 |
mirrored_repositories/attesa_bus | mirrored_repositories/attesa_bus/lib/main.dart | import 'package:attesa_bus/parsing_atac.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'dart:core';
void main() => runApp(new FermateAtacApp());
class FermateAtacApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Tempi di attesa fermata ATAC',
theme: new ThemeData(
primarySwatch: Colors.teal,
),
home: new MyHomePage(title: 'Tempi di attesa fermata ATAC'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AtacFermataInfo _info = new AtacFermataInfo();
TextEditingController _controller = new TextEditingController();
Future<AtacFermataInfo> readAtacWebSite(String fermata) async {
HttpClientRequest request = await HttpClient().postUrl(Uri.parse("https://www.atac.roma.it/function/pg_previsioni_arrivo.asp?pa_src=" + fermata));
HttpClientResponse response = await request.close();
var temp = await response.transform(utf8.decoder).toList();
var result = "";
for (var i = 0; i < temp.length; i++) {
result += temp[i];
}
return AtacPageParser.parse(result);
}
void _refreshInfo() {
var value = _controller.text;
if (value == "") {
setState(() {
_info = new AtacFermataInfo();
});
} else {
readAtacWebSite(value).then((value) {
setState(() {
_info = value;
});
});
}
}
Future _handleRefresh() async {
var c = new Completer();
_refreshInfo();
c.complete(1);
return c.future;
}
Future _submitted(String value) async {
await _handleRefresh();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.teal[900],
title: new Text(widget.title),
),
body: new RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: _info.Linee.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
return new Card(
child: new Column(
children: <Widget>[
new ListTile(
title: TextField(
controller: _controller,
decoration: InputDecoration(
hintText: 'Inserisci il numero della fermata',
suffixIcon: IconButton(
icon: Icon(Icons.search),
onPressed: _refreshInfo,
),
),
onSubmitted: _submitted,
)),
new ListTile(
leading: const Icon(Icons.place),
title: Text(_info.Nome),
)
],
),
);
}
var content = new List<Widget>();
content.add(new Container(
color: Colors.teal,
child: new ListTile(
leading:
const Icon(Icons.directions_bus, color: Colors.white),
title: Text(_info.Linee[index - 1].Nome,
style: new TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white)))));
for (var i = 0;
i < _info.Linee[index - 1].TempiAttesa.length;
i++) {
content.add(ListTile(
title: Text('${_info.Linee[index - 1].TempiAttesa[i]}')));
}
return Card(
child: new Column(
mainAxisSize: MainAxisSize.min, children: content));
}),
));
}
}
| 0 |
mirrored_repositories/attesa_bus | mirrored_repositories/attesa_bus/lib/parsing_atac.dart | import 'package:html/dom.dart';
class AtacPageParser {
static AtacFermataInfo parse(String s) {
try {
Document d = Document.html(s);
var nomeFermata = d.getElementsByClassName("lbl-fermata-nome")[0].querySelector("label");
var allLinee = d.getElementsByClassName("box-linea-percorso-clean");
var result = new AtacFermataInfo();
result.Nome = nomeFermata.innerHtml;
if (allLinee.length > 0) {
var first = allLinee[0];
var parent = first.parent.querySelectorAll("*");
for (var i=0; i<parent.length; i++) {
var n = parent[i];
if (n.classes.contains("box-linea-percorso-clean")) {
var a = n.getElementsByClassName("lbl-linea-percorso-nome")[0];
var linea = new AtacLinea();
linea.Nome = a.innerHtml;
result.Linee.add(linea);
}
else if (n.classes.contains("box-previsioni-informazioni")) {
var a = n.querySelectorAll("*")[1];
result.Linee.last.TempiAttesa.add(a.innerHtml);
}
}
}
return result;
}
catch(e) {
var r = new AtacFermataInfo();
r.Nome = "Fermata non trovata, riprovare.";
return r;
}
}
}
class AtacFermataInfo {
String Nome;
List<AtacLinea> Linee;
AtacFermataInfo() {
Linee = new List<AtacLinea>();
Nome = "";
}
}
class AtacLinea {
String Nome;
List<String> TempiAttesa;
AtacLinea() {
Nome = "";
TempiAttesa = new List<String>();
}
} | 0 |
mirrored_repositories/attesa_bus | mirrored_repositories/attesa_bus/test/widget_test.dart | // This is a basic Flutter widget test.
// To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter
// provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to
// find child widgets in the widget tree, read text, and verify that the values of widget properties
// are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:attesa_bus/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(new FermateAtacApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps | mirrored_repositories/NASA-Hackathon2020/Apps/lib/main.dart |
import 'package:flutter/material.dart';
// import './Screens/description.dart';
// import './widgets/SendAlert.dart';
// import './widgets/contact.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import "package:flutter/services.dart";
import './Screens/auth_screem.dart';
import './providers/auth.dart';
import './Screens/mainscreen.dart';
import "./widgets/Sendcontacts.dart";
void main() async{
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
bool login = prefs.getBool('login');
if (login==null)
login=false;
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp(login));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
final bool login;
MyApp(this.login);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers :[
ChangeNotifierProvider.value(
value: Auth(),),
],
child: Consumer<Auth> (builder: (ctx,auth,_)=> MaterialApp(
routes: {
'/sendcontacts':(context)=>SendContacts(),
},
initialRoute: '/',
debugShowCheckedModeBanner: false,
title: 'Sahayata Project',
theme: ThemeData(
primarySwatch: Colors.red,
accentColor: Colors.black
),
home: (auth.isAuth||login)? MainScreen(auth.token,auth.userId):AuthScreen(),
),
)
);
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/contacttile.dart | import 'package:flutter/material.dart';
import "../widgets/contact_details.dart";
import "../Screens/newcontact.dart";
import "../widgets/contact_list.dart";
class Contacttile extends StatefulWidget {
final List _usercontact;
Contacttile(this._usercontact);
@override
_ContacttileState createState() => _ContacttileState(_usercontact);
}
class _ContacttileState extends State<Contacttile> {
final List _usercontact;
_ContacttileState(this._usercontact);
void _addNewContact(String name, String number) {
final newTx = Contact(
name: name,
number: number,
);
Contact.addcontacts(newTx);
setState(() {
_usercontact.add(newTx);
});
}
void _deleteTx(String number) {
Contact.delete(number);
setState(() {
_usercontact.removeWhere((tx) => tx.number == number);
});
}
@override
Widget build(BuildContext context){
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: Colors.amberAccent[100],
appBar: AppBar(
title:Text("My Contacts"),
leading: IconButton(icon: Icon(Icons.arrow_back),
onPressed:()=> Navigator.of(context).pop()),
),
body: Column(
children: <Widget>[
NewContact(_addNewContact),
Contactlist(_usercontact,_deleteTx),
],
)
);
}
} | 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/routes.dart |
import "dart:async";
import "package:http/http.dart" as http;
import "dart:convert";
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:url_launcher/url_launcher.dart';
import "package:google_maps_flutter/google_maps_flutter.dart";
import 'package:permission/permission.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import "package:google_map_polyline/google_map_polyline.dart";
// import 'package:flutter_map/flutter_map.dart';
class Routes extends StatefulWidget {
final String ph;
final double lat;
final double long;
var currentLocation;
Routes({this.lat,this.long,this.currentLocation,this.ph});
@override
_RoutesState createState() => _RoutesState(lat,long,currentLocation,ph);
}
const double CAMERA_ZOOM = 13;
const double CAMERA_TILT = 0;
const double CAMERA_BEARING = 30;
class _RoutesState extends State<Routes> {
final double lat;
final double long;
final String ph;
LocationData currentLocation;
_RoutesState(this.lat,this.long,this.currentLocation,this.ph);
Completer<GoogleMapController> _controller = Completer();
Set<Marker> _markers = {};
Set<Polyline> _polylines = {};
List<LatLng> polylineCoordinates = [];
PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = "*************";
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children:[ GoogleMap(
myLocationEnabled: true,
compassEnabled: true,
tiltGesturesEnabled: false,
markers: _markers,
polylines: _polylines,
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: LatLng(currentLocation.latitude,currentLocation.longitude), zoom: 14.0),
onMapCreated: onMapCreated),
(ph!=null)?
Container(
height: double.infinity,
width: double.infinity,
child: Container(
alignment:Alignment(0.85, 0.6),
child:
IconButton(icon:
Icon(Icons.phone,
color: Colors.green,
size:60),
onPressed: (){
print(ph);
launch("tel:$ph");
} )
)
):
Container()
]
),
);
}
void onMapCreated(GoogleMapController controller) {
_controller.complete(controller);
setMapPins();
setPolylines();
}
void setMapPins() {
setState(() {
_markers.add(Marker(
markerId: MarkerId('destPin'),
position: LatLng(lat,long),
icon: BitmapDescriptor.defaultMarker));
});
}
@override
Future<List<PointLatLng>> getRouteBetweenCoordinates(String googleApiKey, double originLat, double originLong,
double destLat, double destLong)async
{
List<PointLatLng> polylinePoints = [];
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
originLat.toString() +
"," +
originLong.toString() +
"&destination=" +
destLat.toString() +
"," +
destLong.toString() +
"&mode=walking" +
"&key=$googleApiKey";
var response = await http.get(url);
try {
if (response?.statusCode == 200) {
polylinePoints = decodeEncodedPolyline(json.decode(
response.body)["routes"][0]["overview_polyline"]["points"]);
}
} catch (error) {
throw Exception(error.toString());
}
print(polylinePoints);
return polylinePoints;
}
List<PointLatLng> decodeEncodedPolyline(String encoded)
{
List<PointLatLng> poly = [];
int index = 0, len = encoded.length;
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.codeUnitAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.codeUnitAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
PointLatLng p = new PointLatLng((lat / 1E5).toDouble(), (lng / 1E5).toDouble());
poly.add(p);
}
return poly;
}
setPolylines() async {
List<PointLatLng> result = await polylinePoints?.getRouteBetweenCoordinates(
googleAPIKey,
currentLocation.latitude,
currentLocation.longitude,
lat,
long);
if (result.isNotEmpty) {
result.forEach((PointLatLng point) {
polylineCoordinates.add(LatLng(point.latitude, point.longitude));
});
}
setState(() {
Polyline polyline = Polyline(
polylineId: PolylineId("poly"),
color: Colors.blue,
endCap: Cap.buttCap,
startCap: Cap.roundCap,
patterns: [PatternItem.dot],
points: polylineCoordinates);
_polylines.add(polyline);
});
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/description.dart | import "package:flutter/material.dart";
class Description extends StatelessWidget {
final myController = TextEditingController();
final String type;
Description(this.type);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Descriptions")
),
body:Column(
children: <Widget>[
Text("Type : $type",
style:TextStyle(
fontSize: 20,
color: Colors.black
)),
Flexible(
fit: FlexFit.tight,
flex: 2,
child:TextField(
controller: myController,
)
),
FlatButton(onPressed: ()
{}
,
child: Text("Send request"))
],
)
);
}
} | 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/elevated_card.dart | import "package:flutter/material.dart";
class Elevatedcards extends StatelessWidget {
final icon;
final custom_color;
final String label;
Elevatedcards({this.icon,this.custom_color,this.label});
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Container(
height: deviceSize.height *0.25,
width:deviceSize.width*0.4,
child: Card(
elevation: 5,
borderOnForeground: true,
color: Colors.white,
clipBehavior: Clip.antiAliasWithSaveLayer,
semanticContainer: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(deviceSize.height*0.03)
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(20.0),
child: Icon(icon,
color:custom_color,
size:deviceSize.height*0.123
),
),
Padding(padding: const EdgeInsets.all(3.0),
child: Text(label,
style: TextStyle(
fontSize: deviceSize.height*0.030
),),)
],
)
),
);
}
} | 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/mainscreen.dart |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:location/location.dart';
import 'package:background_fetch/background_fetch.dart';
import 'package:provider/provider.dart';
import 'package:sms/sms.dart';
import 'package:shared_preferences/shared_preferences.dart';
import "package:http/http.dart" as http;
import 'dart:convert';
import 'package:url_launcher/url_launcher.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import "../Screens/contacttile.dart";
import "../widgets/SendAlert.dart";
import "../widgets/Panicbutton.dart";
import '../widgets/contact_details.dart';
import "./elevated_card.dart";
import "./routes.dart";
import "../main.dart";
class MainScreen extends StatefulWidget {
final String tokenno;
final String userid;
MainScreen(this.tokenno,this.userid);
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
final FirebaseMessaging _messaging=FirebaseMessaging();
var _scaffoldKey = new GlobalKey<ScaffoldState>();
@override
void initState(){
final String serverToken = '***********************';
super.initState();
_messaging.getToken().then((token){
_switchbutton(token);
});
_messaging.configure(
onMessage: (Map<String, dynamic> message) async {
if(message["notification"]["title"]=="Confirmation"){
print("yeta badhnu parne ho k reh");
alertState.setState(() { alertState.pcounter+=1;});
return;
}
var location = new Location();
LocationData currentLocation = await location.getLocation();
print(message);
double user_lat=double.parse(message["data"]["latitude"]);
double user_long=double.parse(message["data"]["longitude"]);
print(user_lat);
print(user_long);
String name=message["data"]["name"];
String description=message["data"]["Description"];
String phone_number=message["data"]["phone_no"];
print(phone_number);
print(name);
print(description);
Widget cancelButton = RaisedButton(
color: Colors.white,
child: Text("No"),
onPressed: () {
Navigator.of(context).pop();
},
);
Widget continueButton = RaisedButton(
color:Colors.red,
child: Text("Navigate me"),
onPressed: ()async {
var result=await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'registration_ids': [message["data"]["return_token"]],
'notification': <String, dynamic>{
'title': 'Confirmation',
'body':'',
},
},
),
);
var outcome=jsonDecode(result.body);
print(outcome);
Navigator.of(context).pop();
Navigator.of(context).push(MaterialPageRoute(builder: (_){
return Routes(long: user_long,lat: user_lat,currentLocation: currentLocation,ph:phone_number);
}));
},
);
// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("Help Alert"),
content: Text("$name need your help.\nDescription:$description.\n Do you wish to help?"),
actions: [
cancelButton,
continueButton,
],
);
new Future.delayed(Duration.zero, (){ showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
});
},
onLaunch: (Map<String, dynamic> message) async {
if(message["notification"]["title"]=="confirmation"){
alertState.setState(() { alertState.pcounter+=1;});
return;
}
var location = new Location();
LocationData currentLocation = await location.getLocation();
double user_lat=double.parse(message["data"]["latitude"]);
double user_long=double.parse(message["data"]["longitude"]);
String phone_number=message["data"]["phone_no"];
var result=await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'registration_ids': [message["data"]["return_token"]],
'notification': <String, dynamic>{
'title': 'Confirmation',
'body':'',
},
},
),
);
print(result.body);
Navigator.of(context).push(MaterialPageRoute(builder: (_){
return Routes(long: user_long,lat: user_lat,currentLocation: currentLocation,ph:phone_number);
}));
},
onResume: (Map<String, dynamic> message) async {
var location = new Location();
LocationData currentLocation = await location.getLocation();
double user_lat=double.parse(message["data"]["latitude"]);
double user_long=double.parse(message["data"]["longitude"]);
String phone_number=message["data"]["phone_no"];
var result=await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'registration_ids': [message["data"]["return_token"]],
'notification': <String, dynamic>{
'title': 'Confirmation',
'body':'',
},
},
),
);
print(result.body);
Navigator.of(context).push(MaterialPageRoute(builder: (_){
return Routes(long: user_long,lat: user_lat,currentLocation: currentLocation,ph:phone_number);
}));
},
);
}
Future<FirebaseUser> getFirebaseUser() async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if(user==null)
{
final FirebaseAuth _auth = FirebaseAuth.instance;
SharedPreferences prefs = await SharedPreferences.getInstance();
String email = prefs.getString('email');
String password=prefs.getString('password');
_auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user2 = await FirebaseAuth.instance.currentUser();
print(user2);
return user2;
}
else
return user;
}
_database(context,{forcontacts=false}) async {
LocationData currentLocation;
final firestore=Firestore.instance;
var location = new Location();
try {
currentLocation = await location.getLocation();
double lat = currentLocation.latitude;
double lng = currentLocation.longitude;
final coordinates = new Coordinates(lat, lng);
if (forcontacts)
{
return coordinates;
}
var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
} catch (e) {
print("error");
print(e);
}
}
Future<void> callstring(context,String text,String type,{String alternalte})
async{
Coordinates corde= await _database(context,forcontacts: true);
double lat=corde.latitude;
double long=corde.longitude;
final String url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&rankby=distance&type=$type&keyword=$text&key=*******';
print(url);
var response = await http.get(url, headers: {"Accept": "application/json"});
print(response.body);
List data=json.decode(response.body)["results"];
String phone_no=null;
if (data!=[]){
print(data);
String place_id=data[0]["place_id"];
final String detailUrl =
"https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id&fields=name,formatted_phone_number&key=******************";
var response2 = await http.get(detailUrl, headers: {"Accept": "application/json"});
print("-------Second Part------");
print(response2.body);
var result=json.decode(response2.body)["result"];
if(result!=null)
{
print(result);
phone_no=result["formatted_phone_number"];
print(result["name"]);
print(phone_no);
if(phone_no==null)
{
phone_no=alternalte;
}
}
else{
phone_no=alternalte;
}
}
else
phone_no=alternalte;
print("So far working");
launch("tel:$phone_no");
print("working??");
}
void backgroundFetchHeadlessTask(String taskId) async {
print('[BackgroundFetch] Headless event received.');
BackgroundFetch.finish(taskId);
}
Future<bool> _switchbutton(String fcm_tokens) async {
BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
requiresBatteryNotLow: true,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.ANY,
), (String taskId) async {
Coordinates corde= await _database(context,forcontacts: true);
print("data sent");
var firestore=Firestore.instance;
FirebaseUser user=await getFirebaseUser();
print(user);
var token= await user.getIdToken(refresh: true);
String token_id =token.token;
String fcm_token=fcm_tokens;
print("here is the token");
print(token_id);
firestore.collection('markers').document(user.uid).setData({'Location':new GeoPoint(corde.latitude, corde.longitude),
'Token':token_id,
"fcm_token":fcm_token,
});
print("working");
});
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('Sendloc', true);
bool loc=prefs.getBool('Sendloc');
return loc;
}
_contactsend(context) async{
List contactList=await Contact.getdatabase();
print("so far so good");
print(contactList);
print(contactList.length);
if (contactList.length==0)
{
return showDialog<void>(
context:context ,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('No contacts'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[Text("You don't have any contacts please add some contacts and come back")],
),
),
actions: <Widget>[
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
else {
SharedPreferences prefs = await SharedPreferences.getInstance();
String name=prefs.getString("name");
Coordinates cord= await _database(context,forcontacts: true);
double lat=cord.latitude;
double long=cord.longitude;
String message = "$name is in trouble, find him in:http://maps.google.com/?q=$lat,$long";
print(message);
_sendSMS(message,contactList,context);
}
}
void _sendSMS(String send_message, List<Contact> recipents,context) async {
SmsSender sender = new SmsSender();
for (int i=0;i<recipents.length;i++)
{
String address=recipents[i].number;
String name=recipents[i].name;
SmsMessage message = new SmsMessage(address, send_message);
message.onStateChanged.listen((state) {
if (state == SmsMessageState.Sent) {
} else if (state == SmsMessageState.Delivered) {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text("SMS is delivered to $name"),
duration: Duration(seconds: 5),
)
);
}
else if(state==SmsMessageState.Fail)
{
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text("Failed sending SMS to $name"),
duration: Duration(seconds: 5),
action: SnackBarAction(label: "Resend",
textColor: Colors.blue,
onPressed: (){
SmsMessage message = new SmsMessage(address, send_message);
}),
)
);
}
});
sender.sendSms(message);
}
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.red,
centerTitle: true,
title: Text("Make a SOS request",
style:TextStyle(
fontWeight:FontWeight.w600,
fontSize: 24,
)
),
actions: <Widget>[
IconButton(icon: Icon(Icons.group_add),
onPressed: () async {
List contactList=await Contact.getdatabase();
Navigator.of(context).push(MaterialPageRoute(builder: (_){
return Contacttile(contactList);
}));
}
)
],
),
body: SingleChildScrollView(
child:Container(
height:MediaQuery.of(context).size.height*0.9,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height*0.5,
child: GridView.count(crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
children: <Widget>[
InkWell(
splashColor: Colors.amber,
autofocus: true,
onDoubleTap: (){
callstring(context, "fire brigade","",alternalte: "102");
},
child:Elevatedcards(icon: Icons.whatshot,custom_color: Colors.amberAccent,label: "Fire",),),
InkWell(
splashColor: Colors.lightBlue,
autofocus: true,
onDoubleTap: (){
callstring(context, "Police Station","police",alternalte: "100");
},
child:Elevatedcards(icon:Icons.face,custom_color:Colors.lightBlue,label:"Police"),),
InkWell(
splashColor: Colors.redAccent,
autofocus: true,
onDoubleTap: (){
callstring(context, "Hospital","hospital",alternalte: "911");
},
child:Elevatedcards(icon:Icons.local_hospital,custom_color:Colors.red,label:"Hospital")),
InkWell(
splashColor: Colors.amberAccent[100],
autofocus: true,
onDoubleTap: (){callstring(context, "Gurudwara","",alternalte: "911");},
child:Elevatedcards(icon:Icons.home,custom_color:Colors.orange,label:"Shelter")),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
autofocus: true,
onDoubleTap:()async{
await _database(context);
Coordinates corde= await _database(context,forcontacts: true);
Navigator.of(context).push(MaterialPageRoute(builder: (_){
return SendAert(corde);
})
);
},
child:PanicButton(helptext: "SOS",backgroundColor: Colors.red,health: true,)
),
InkWell(
autofocus: true,
onDoubleTap:()async{
_contactsend(context);
Navigator.pushNamed(context, '/sendcontacts',arguments:"health");},
child:PanicButton(helptext: " Contacts",
backgroundColor: Colors.red,health:false
)
)
]
),
Padding(
padding: const EdgeInsets.only(top:20.0),
child: ButtonTheme(
minWidth: 150,
height: 80,
child:
RaisedButton(onPressed: ()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("login", false);
final FirebaseAuth _auth = FirebaseAuth.instance;
_auth.signOut();
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
return MyApp(false);
}
)
);
},
padding: EdgeInsets.all(10),
autofocus: true,
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.white,
child: Text("Sign out",
style: TextStyle(
color:Colors.blue,
fontSize:20
),)
),
),
),
]
)
)
)
);
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/newcontact.dart | import 'package:flutter/material.dart';
import '../widgets/contact_details.dart';
class NewContact extends StatelessWidget {
final Function addTx;
final titleController = TextEditingController();
final numberController = TextEditingController();
NewContact(this.addTx);
@override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Name'),
controller: titleController,
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Number'),
controller: numberController,
),
FlatButton(
child: Text('Add Contact'),
textColor: Colors.purple,
onPressed: () {
if (titleController.text.isEmpty||numberController.text.isEmpty) {
return;}
else{
addTx(
titleController.text,
numberController.text);
}
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/auth_screem.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../providers/auth.dart';
import '../widgets/CustomTextField.dart';
import '../widgets/http_exception.dart';
enum AuthMode { Signup, Login}
class AuthScreen extends StatelessWidget {
static const routeName = '/auth';
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Scaffold(
// resizeToAvoidBottomInset: false,
body: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
),
),
SingleChildScrollView(
child: Container(
height: deviceSize.height,
width: deviceSize.width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 0.5*deviceSize.height,
width: 0.9*deviceSize.width,
child: AuthCard(),
),
],
),
),
),
],
),
);
}
}
class AuthCard extends StatefulWidget {
const AuthCard({
Key key,
}) : super(key: key);
@override
_AuthCardState createState() => _AuthCardState();
}
class _AuthCardState extends State<AuthCard> {
final GlobalKey<FormState> _formKey = GlobalKey();
AuthMode _authMode = AuthMode.Login;
Map<String, String> _authData = {
'email': '',
'password': '',
'location':" ",
'adharno':' ',
};
double latt;
double long;
var _isLoading = false;
final _passwordController = TextEditingController();
void _showErrorDialog(String message) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An Error Occurred!'),
content: Text(message),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
);
}
Future<void> _submit() async {
if (!_formKey.currentState.validate()) {
// Invalid!
return;
}
_formKey.currentState.save();
setState(() {
_isLoading = true;
});
try {
if (_authMode == AuthMode.Login) {
// Log user in
await Provider.of<Auth>(context, listen: false).login(
_authData['email'],
_authData['password'],
);
} else {
// Sign user up
await Provider.of<Auth>(context, listen: false).signup(
_authData['email'],
_authData['password'],
_authData["adharno"],
latt,
long,
);
}
} on HttpException catch (error) {
var errorMessage = 'Authentication failed';
if (error.toString().contains('EMAIL_EXISTS')) {
errorMessage = 'This email address is already in use.';
} else if (error.toString().contains('INVALID_EMAIL')) {
errorMessage = 'This is not a valid email address';
} else if (error.toString().contains('WEAK_PASSWORD')) {
errorMessage = 'This password is too weak.';
} else if (error.toString().contains('EMAIL_NOT_FOUND')) {
errorMessage = 'Could not find a user with that email.';
} else if (error.toString().contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid password.';
}
_showErrorDialog(errorMessage);
} catch (error) {
const errorMessage =
'Could not authenticate you. Please try again later.';
_showErrorDialog(errorMessage);
}
setState(() {
_isLoading = false;
});
}
void _switchAuthMode() {
if (_authMode == AuthMode.Login) {
setState(() {
_authMode = AuthMode.Signup;
});
} else {
setState(() {
_authMode = AuthMode.Login;
});
}
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 8.0,
child: Container(
height: _authMode == AuthMode.Signup ? 460 : 400,
constraints:
BoxConstraints(minHeight: _authMode == AuthMode.Signup ? 460 : 400),
width: deviceSize.width * 0.75,
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
CustomTextfield(
hint: "Enter your Id",
icon: Icon(Icons.mail),
validator: (input)=>input.isEmpty? "Email required":null,
onSaved: (value) {
_authData['email'] = value;
},
),
CustomTextfield(
hint: "Enter your password",
icon: Icon(Icons.lock),
obsecure: true,
controller: _passwordController,
onSaved: (value) {
_authData['password'] = value;
},
validator: (value) {
if (value.isEmpty || value.length < 5) {
return 'Password is too short!';
}
},
),
if (_authMode == AuthMode.Signup)
CustomTextfield(
hint: 'Confirm Password',
obsecure: true,
validator: _authMode == AuthMode.Signup
? (value) {
if (value != _passwordController.text) {
return 'Passwords do not match!';
}
}
: null,
),
if (_authMode == AuthMode.Signup)
CustomTextfield(
hint: "Enter your phone number ",
icon: Icon(Icons.contacts),
validator: (input)=>input.isEmpty? "phone no is required":null,
onSaved: (value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('phone_no',value);
_authData['adharno'] = value;
},
),
if (_authMode == AuthMode.Signup)
CustomTextfield(
hint: "Enter your name ",
icon: Icon(Icons.contacts),
validator: (input)=>input.isEmpty? "Name is required":null,
onSaved: (value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('name',value);
},
),
SizedBox(
height: 20,
),
(_isLoading)?
CircularProgressIndicator()
:
RaisedButton(
child:
Text(_authMode == AuthMode.Login ? 'LOGIN' : 'SIGN UP'),
onPressed: _submit,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
padding:
EdgeInsets.symmetric(horizontal: 30.0, vertical: 8.0),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).primaryTextTheme.button.color,
),
FlatButton(
child: Text(
'${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} INSTEAD'),
onPressed: _switchAuthMode,
padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 4),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
textColor: Theme.of(context).primaryColor,
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/Screens/FIR.dart | import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
class UserFir{
final String title;
final DateTime date;
final String description;
final String location;
final String mailadress;
final String adharno;
UserFir({this.date,this.description,this.location,this.mailadress,this.title,this.adharno});
}
class FIR extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title:Text("Complains",
style:TextStyle(
color:Colors.blue
)),
leading: IconButton(icon: Icon(Icons.arrow_back), onPressed: ()=>Navigator.pop(context)),
),
body:FIRlist(),
);
}
}
class FIRlist extends StatefulWidget {
@override
_FIRlistState createState() => _FIRlistState();
}
class _FIRlistState extends State<FIRlist> {
static List<UserFir> Fir_list=[];
@override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height*0.63,
child: Fir_list.isEmpty
?Padding(
padding: const EdgeInsets.only(top:15.0),
child: Text("No FIR have been added yet",
style: TextStyle(
fontSize: 28
),),
):
ListView.builder(
itemBuilder: (ctx, index){
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child:ListTile(
title: Text(
'${Fir_list[index].title}',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.black,
),
),
subtitle: Text(Fir_list[index].date.toString())
),
);
}
)
);
}
} | 0 |
mirrored_repositories/NASA-Hackathon2020/Apps/lib | mirrored_repositories/NASA-Hackathon2020/Apps/lib/providers/auth.dart | import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../widgets/http_exception.dart';
class Auth with ChangeNotifier {
String _token;
DateTime _expiryDate;
String _userId;
bool get isAuth {
return token != null;
}
String get token {
if (_expiryDate != null &&
_expiryDate.isAfter(DateTime.now()) &&
_token != null) {
return _token;
}
return null;
}
String get userId {
return _userId;
}
Future<void> _authenticate(
String email, String password, String urlSegment,{String adharno,double lattitude, double longitude}) async {
print(urlSegment);
final url ='https://www.googleapis.com/identitytoolkit/v3/relyingparty/$urlSegment?key=***********************';
try {
final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
'returnSecureToken': true,
},
),
);
print("Sent ");
final responseData = json.decode(response.body);
print(responseData);
if (responseData['error'] != null) {
throw HttpException(responseData['error']['message']);
}
if (urlSegment=="signupNewUser")
{
print("working");
Firestore.instance.collection('User').add({ 'adharno': adharno, 'mailaddress': email,
});
}
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('login', true);
prefs.setString("email", email);
prefs.setString("password", password);
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now().add(
Duration(
seconds: int.parse(
responseData['expiresIn'],
),
),
);
notifyListeners();
} catch (error) {
throw error;
}
}
Future<void> signup(String email, String password,String adharno, double lattitude,double longitude) async {
return _authenticate(email, password, 'signupNewUser',adharno: adharno,lattitude: lattitude,longitude: longitude);
}
Future<void> login(String email, String password) async {
return _authenticate(email, password, 'verifyPassword');
}
}
| 0 |
mirrored_repositories/NASA-Hackathon2020/Apps | mirrored_repositories/NASA-Hackathon2020/Apps/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Calculator | mirrored_repositories/Calculator/lib/calculator.dart | import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart';
class Calculator extends StatefulWidget {
const Calculator({super.key});
@override
State<Calculator> createState() => _CalculatorState();
}
class _CalculatorState extends State<Calculator> {
// String lastInput = "0";
String equation = "0";
String result = "0";
String expression = "";
double equationFontSize = 35.0;
double resultFontSize = 45.0;
buttonPressed(String buttonText){
setState(() {
if (buttonText == "C"){
equation = "0";
result = "0";
}else if (buttonText == "<- "){
equation = equation.substring(0,equation.length - 1);
if (equation == ""){
equation = "0";
}
}else if (buttonText == "x^2"){
equation += "^2";
}else if (buttonText == "="){
expression = equation;
expression = expression.replaceAll('x','*');
try{
Parser p = Parser();
Expression exp = p.parse(expression);
ContextModel cm = ContextModel();
result = '${exp.evaluate(EvaluationType.REAL,cm)}';
}catch(e){
result = "Error";
}
}else {
equationFontSize = 45.0;
resultFontSize = 35.0;
if (equation == "0"){
equation = buttonText;
}else{
equation = equation + buttonText;
}
}
});
}
Widget buildButton(String buttonText, double buttonHeight, Color buttonColor) {
return Container(
height: MediaQuery.of(context).size.height * 0.1 * buttonHeight,
color: buttonColor,
child: TextButton(
style: TextButton.styleFrom(backgroundColor: buttonColor),
onPressed: () => buttonPressed(buttonText),
child: Text(
buttonText,
style: const TextStyle(
fontSize: 32.0,
fontWeight: FontWeight.normal,
color: Colors.white,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
const SizedBox(
height: 5,
),
Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.fromLTRB(10, 20, 10, 0),
child: Text(equation,style: TextStyle(fontSize: equationFontSize)),
),
Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.fromLTRB(10, 30, 10, 0),
child: Text(result,style: TextStyle(fontSize: resultFontSize)),
),
const Expanded(
child: Divider(),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: MediaQuery.of(context).size.width * .75,
child: Table(
children: [
TableRow(
children: [
buildButton("x^2", 1, const Color.fromARGB(255, 89, 150, 255) ),
buildButton("<- ", 1, const Color.fromARGB(255, 89, 150, 255) ),
buildButton("C", 1, const Color.fromARGB(255, 89, 150, 255) ),
]
),
TableRow(
children: [
buildButton("7", 1, Colors.black ),
buildButton("8", 1, Colors.black ),
buildButton("9", 1, Colors.black ),
]
),
TableRow(
children: [
buildButton("4", 1, Colors.black ),
buildButton("5", 1, Colors.black ),
buildButton("6", 1, Colors.black ),
]
),
TableRow(
children: [
buildButton("1", 1, Colors.black ),
buildButton("2", 1, Colors.black ),
buildButton("3", 1, Colors.black ),
]
),
TableRow(
children: [
buildButton(".", 1, Colors.black ),
buildButton("0", 1, Colors.black ),
buildButton("00", 1, Colors.black ),
]
)
],
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.25,
child: Table(
children: [
TableRow(
children: [
buildButton("/",1,const Color.fromARGB(255, 182, 182, 182)),
]
),
TableRow(
children: [
buildButton("*",1,const Color.fromARGB(255, 182, 182, 182)),
]
),
TableRow(
children: [
buildButton("-",1,const Color.fromARGB(255, 182, 182, 182)),
]
),
TableRow(
children: [
buildButton("+",1,const Color.fromARGB(255, 182, 182, 182)),
]
),
TableRow(
children: [
buildButton("=",1,Color.fromARGB(255, 255, 190, 105)),
]
)
],
),
)
],
)
],
),
);
}
} | 0 |
mirrored_repositories/Calculator | mirrored_repositories/Calculator/lib/main.dart | import 'package:calculator/calculator.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Calculator(),
);
}
}
| 0 |
mirrored_repositories/Calculator | mirrored_repositories/Calculator/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:calculator/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/payment_app | mirrored_repositories/payment_app/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_rave/flutter_rave.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
color: Colors.orangeAccent,
theme: ThemeData(primaryColor: Colors.orangeAccent),
title: 'Flutterwave',
debugShowCheckedModeBanner: false,
home: MyHomePage(title: 'Flutterwave'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
centerTitle: true,
),
body: Center(
child: Builder(
builder: (context) => SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10),
child: InkWell(
onTap: () => _pay(context),
child: Card(
color: Colors.orangeAccent,
elevation: 15,
child: Container(
height: 250,
width: MediaQuery.of(context).size.width,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Card Payment",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 10,
),
Icon(
Icons.payment,
color: Colors.black,
size: 30,
)
],
),
),
),
),
),
),
),
),
),
);
}
_pay(BuildContext context) {
final snackBar_onFailure = SnackBar(content: Text('Transaction failed'));
final snackBar_onClosed = SnackBar(content: Text('Transaction closed'));
final _rave = RaveCardPayment(
isDemo: true,
encKey: "c53e399709de57d42e2e36ca",
publicKey: "FLWPUBK-d97d92534644f21f8c50802f0ff44e02-X",
transactionRef: "hvHPvKYaRuJLlJWSPWGGKUyaAfWeZKnm",
amount: 100,
email: "[email protected]",
onSuccess: (response) {
print("$response");
print("Transaction Successful");
if (mounted) {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text("Transaction Sucessful!"),
backgroundColor: Colors.green,
duration: Duration(
seconds: 5,
),
),
);
}
},
onFailure: (err) {
print("$err");
print("Transaction failed");
Scaffold.of(context).showSnackBar(snackBar_onFailure);
},
onClosed: () {
print("Transaction closed");
Scaffold.of(context).showSnackBar(snackBar_onClosed);
},
context: context,
);
_rave.process();
}
}
| 0 |
mirrored_repositories/payment_app | mirrored_repositories/payment_app/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:payment/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/drinkable | mirrored_repositories/drinkable/lib/root.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
// providers
import './providers/auth_provider.dart';
// screens
import './screens/auth_screen.dart';
// widgets
import './widgets/custom_drawer.dart';
class Root extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<AuthProvider>(
builder: (context, authProvider, child) {
User user = authProvider.user;
if(user==null){
return AuthScreen();
}
return CustomDrawer();
},
);
}
} | 0 |
mirrored_repositories/drinkable | mirrored_repositories/drinkable/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// providers
import './providers/home_provider.dart';
import './providers/auth_provider.dart';
import './providers/statistics_provider.dart';
// screens
import './root.dart';
import './screens/data_entry_screen.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await SystemChrome.setPreferredOrientations(
<DeviceOrientation>[
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp
]
);
FlutterLocalNotificationsPlugin notificationsPlugin = FlutterLocalNotificationsPlugin();
AndroidInitializationSettings android = AndroidInitializationSettings('notification_icon');
IOSInitializationSettings ios = IOSInitializationSettings();
InitializationSettings settings = InitializationSettings(
android,ios
);
await notificationsPlugin.initialize(
settings,
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<AuthProvider>(
create: (context) => AuthProvider(),
),
ChangeNotifierProxyProvider<AuthProvider,HomeProvider>(
create: (context) => HomeProvider(),
update: (context, authProvider, homeProvider) => homeProvider..update(authProvider.user),
),
ChangeNotifierProxyProvider<AuthProvider,StatisticsProvider>(
create: (context) => StatisticsProvider(),
update: (context, authProvider, statisticsProvider) => statisticsProvider..update(authProvider.user),
)
],
child: MaterialApp(
//showPerformanceOverlay: true,
title: 'Drinkable',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
pageTransitionsTheme: PageTransitionsTheme(
builders: {
TargetPlatform.android : CupertinoPageTransitionsBuilder()
}
),
),
home: Root(),
routes: {
DataEntryScreen.routeName : (ctx)=>DataEntryScreen(),
},
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/custom_drawer.dart | import 'package:google_fonts/google_fonts.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart';
import 'package:firebase_auth/firebase_auth.dart';
// providers
import '../providers/auth_provider.dart';
// screens
import '../screens/profile_screen.dart';
import '../screens/home_screen.dart';
import '../screens/scatistics_screen.dart';
class CustomDrawer extends StatefulWidget {
static const routeName = 'drawer';
@override
_CustomDrawerState createState() => _CustomDrawerState();
}
class _CustomDrawerState extends State<CustomDrawer> with SingleTickerProviderStateMixin {
bool _isDrawerOpened = false;
int screen = 0;
AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 350),
);
changeStatusBar(false);
}
void changeStatusBar(bool isOpened){
if(isOpened){
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.light
));
}else{
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark,
));
}
}
void open(){
changeStatusBar(true);
_animationController.forward();
setState(() {
_isDrawerOpened = true;
});
}
void close()async{
await _animationController.reverse();
changeStatusBar(false);
setState(() {
_isDrawerOpened = false;
});
}
void selectItem(int index){
if(index!=screen){
setState(() {
screen = index;
});
}
close();
}
@override
Widget build(BuildContext context) {
List<Widget> screens = [
HomeScreen(openDrawer: open,),
StatisticsScreen(openDrawer: open,),
ProfileScreen(openDrawer: open,)
];
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Color.fromARGB(255,0, 11, 33),
body: Stack(
children: [
Container(
padding: EdgeInsets.symmetric(
vertical: 35
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Consumer<AuthProvider>(
builder: (context, value, child) {
User user = value.user;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
radius: 20,
backgroundImage: NetworkImage(user.photoURL),
),
SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Hello',style: GoogleFonts.poppins(color: Colors.white54,fontSize: 14),),
SizedBox(height: 1,),
Text(user.displayName.split(' ')[0],style: GoogleFonts.poppins(color: Colors.white,fontSize: 17,fontWeight: FontWeight.w500))
],
)
],
);
},
),
IconButton(
icon: Icon(Icons.close,color: Colors.white60,size: 20,),
onPressed: close,
)
],
),
),
Expanded(
child: ListView(
padding: EdgeInsets.only(top: 40),
children: [
MenuItem(
icon: Icons.home,
title: 'Home',
onTap: (){
selectItem(0);
},
),
MenuItem(
icon: Icons.show_chart,
title: 'Statistics',
onTap: (){
selectItem(1);
},
),
MenuItem(
icon: Icons.account_circle,
title: 'Profile',
onTap: (){
selectItem(2);
},
),
MenuItem(
icon: Icons.exit_to_app,
title: 'Log Out',
onTap: (){
Provider.of<AuthProvider>(context,listen: false).signOut();
},
),
],
),
)
],
),
),
AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
return Transform(
transform: Matrix4.identity()
..scale(1.0-(0.2*_animationController.value))
..translate(0.0,size.height*0.80*_animationController.value,0.0)
..setEntry(3, 2, 0.002)
..rotateX(0.15*_animationController.value),
origin: Offset(0,0),
alignment: Alignment.center,
// comment the child and uncomment the commented child to get the curved app drawer
child: child,
// child: ClipRRect(
// borderRadius: BorderRadius.circular(20*_animationController.value),
// child: AbsorbPointer(
// absorbing: _isDrawerOpened,
// child: screens[screen],
// ),
// )
);
},
child: AbsorbPointer(
absorbing: _isDrawerOpened,
child: screens[screen],
)
)
]
),
);
}
}
class MenuItem extends StatelessWidget {
final IconData icon;
final String title;
final Function onTap;
MenuItem({this.icon,this.title,this.onTap});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: this.onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 13,horizontal: 35),
child: Row(
children: [
Icon(this.icon,color: Colors.white,size: 21,),
SizedBox(width: 15,),
Text(this.title,style: GoogleFonts.poppins(color: Colors.white,fontSize: 14),),
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/three_layer_background.dart | import 'package:flutter/material.dart';
class ThreeLayerBackground extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Stack(
children: [
Align(
alignment: Alignment.bottomCenter,
child: ClipPath(
clipper: MyClipper(),
child: Container(
height: constraints.maxHeight,
color: Color.fromARGB(255,11, 209, 252),
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: ClipPath(
clipper: MyClipper(),
child: Container(
height: constraints.maxHeight*0.75,
color: Color.fromARGB(255, 0, 140, 238),
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: ClipPath(
clipper: MyClipper(),
child: Container(
height: constraints.maxHeight*0.50,
color: Color.fromARGB(255, 0, 60, 192),
),
),
)
],
);
},
);
}
}
class MyClipper extends CustomClipper<Path>{
@override
Path getClip(Size size) {
Path path = Path();
path.lineTo(0,size.height);
path.lineTo(size.width, size.height);
path.lineTo(size.width, 30);
path.quadraticBezierTo(size.width/2, -1, 0, 0);
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/loading_screen.dart | import 'package:flutter/material.dart';
// widgets
import './custom_progress_indicator.dart';
class LoadingScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CustomProgressIndicatior()
),
);
}
}
| 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/weather_suggestion.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts/google_fonts.dart';
// providers
import '../providers/home_provider.dart';
// values
import '../values/weather_icons.dart';
class WeatherSuggestion extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Weather',
style: GoogleFonts.poppins(fontSize: 20),
),
SizedBox(height: 18,),
Consumer<HomeProvider>(
builder: (context, value, child) {
Map<String,dynamic> weather = value.weather;
return Row(
children: [
Container(
padding: EdgeInsets.all(25),
decoration: BoxDecoration(
color: Color.fromARGB(255, 37, 90, 210),
borderRadius: BorderRadius.circular(8)
),
child: Image.asset(
weatherIcons[
weather['icon'].toString().split('')[0]
+weather['icon'].toString().split('')[1]
],
width: 40,
),
),
SizedBox(width: 20,),
Container(
width: 140,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
text: TextSpan(
style: GoogleFonts.poppins(
color: Colors.black,fontSize: 17,
),
children: [
TextSpan(text: 'It\'s ',style: GoogleFonts.poppins(fontWeight: FontWeight.w300)),
TextSpan(text: weather['description'],style: GoogleFonts.poppins(fontWeight: FontWeight.w700)),
TextSpan(text: ' today!',style: GoogleFonts.poppins(fontWeight: FontWeight.w300)),
]
),
),
SizedBox(height: 11,),
Text(
'Dont\'t forget to take the water bottle with you.',
style: GoogleFonts.poppins(
height: 1.5,
color: Colors.black.withOpacity(0.6),
fontSize: 12
),
)
],
),
)
],
);
},
),
],
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/water_effect.dart | import 'package:flutter/material.dart';
import 'dart:math';
class WaterEffect extends StatefulWidget {
@override
_WaterEffectState createState() => _WaterEffectState();
}
class _WaterEffectState extends State<WaterEffect> with SingleTickerProviderStateMixin {
AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 5),
);
_animationController.repeat();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
List<Offset> points1 = [];
List<Offset> points2 = [];
for(double i=0;i<=constraints.maxWidth;i++){
double val = 15*sin(2*pi*(_animationController.value + (i/constraints.maxWidth)));
double val2 = 15*sin(2*pi*(_animationController.value + (1-(i/constraints.maxWidth))));
points1.add(Offset(i,constraints.maxWidth-15+val));
points2.add(Offset(constraints.maxWidth - i,15+val2));
}
return ClipPath(
clipper: WaveClipper(points1,points2),
child: Container(
constraints: constraints,
child: Stack(
alignment: Alignment.topCenter,
children: [
Container(
width: constraints.maxWidth,
height: constraints.maxWidth,
color: Color.fromARGB(255, 0, 60, 192),
),
],
),
),
);
},
);
},
);
}
}
class WaveClipper extends CustomClipper<Path> {
List<Offset> offsets1;
List<Offset> offsets2;
WaveClipper(this.offsets1,this.offsets2);
@override
Path getClip(Size size) {
Path path = Path();
path.lineTo(offsets1[0].dx,offsets1[0].dy);
path.addPolygon(offsets1, false);
path.lineTo(offsets2[0].dx,offsets2[0].dy);
path.addPolygon(offsets2, false);
path.lineTo(offsets2[offsets2.length-1].dx,offsets2[offsets2.length-1].dy);
path.lineTo(offsets1[0].dx,offsets1[0].dy);
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => true;
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/custom_progress_indicator.dart | import 'package:flutter/material.dart';
class CustomProgressIndicatior extends StatefulWidget {
@override
_CustomProgressIndicatiorState createState() => _CustomProgressIndicatiorState();
}
class _CustomProgressIndicatiorState extends State<CustomProgressIndicatior> with SingleTickerProviderStateMixin {
AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: (3*0.5*2222).toInt())
);
_animationController.repeat();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CircularProgressIndicator(
valueColor: TweenSequence(
<TweenSequenceItem<Color>>[
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(Color.fromARGB(255, 0, 60, 192)),
weight: 33.33,
),
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(Color.fromARGB(255, 0, 140, 238)),
weight: 33.33,
),
TweenSequenceItem<Color>(
tween: ConstantTween<Color>(Color.fromARGB(255,11, 209, 252)),
weight: 33.33,
),
],
).animate(_animationController),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/goal_and_add.dart | import 'package:flutter/material.dart';
// widgets
import './daily_amout_dial.dart';
import './daily_goal_amount.dart';
import './water_effect.dart';
class GoalAndAdd extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Container(
constraints: constraints,
child: Stack(
alignment: Alignment.center,
children: [
WaterEffect(),
Padding(
padding: const EdgeInsets.symmetric(horizontal:20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
DailyGoalAmount(),
SizedBox(height: 25,),
DailyAmountDial()
],
),
],
),
)
],
)
);
},
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/daily_goal_amount.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts/google_fonts.dart';
// providers
import '../providers/home_provider.dart';
class DailyGoalAmount extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(2),
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 15,
vertical: 12
),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
border: Border(left: BorderSide(color: Colors.white,width: 2)),
),
child: Row(
children: [
Text(
'Goal',
style: GoogleFonts.poppins(
color: Colors.white.withOpacity(0.8),
fontSize: 19,
fontWeight: FontWeight.w300
),
),
SizedBox(width: 15,),
Consumer<HomeProvider>(
builder: (context, provider, child) {
return Text(
provider.dailyTarget.toString(),
style: GoogleFonts.poppins(
color: Colors.white,
fontSize: 19,
fontWeight: FontWeight.w700
)
);
},
)
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/custom_form_field.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class CustomFormField extends StatelessWidget {
final String label;
final Widget child;
CustomFormField({this.child,this.label});
@override
Widget build(BuildContext context) {
return Container(
height: 60,
child: Stack(
children: [
Container(
width: double.infinity,
height: double.infinity,
margin: EdgeInsets.only(top: 6),
padding: EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
border: Border.all(color: Colors.black.withOpacity(0.3),width: 1.1),
borderRadius: BorderRadius.circular(4)
),
alignment: Alignment.centerLeft,
child: child
),
Positioned(
left: 14,
child: Container(
color: Colors.white,
padding: EdgeInsets.symmetric(horizontal: 3),
child: Text(
label,
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w500
),
)
),
)
],
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/weekly_statistics_graph.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
// models
import '../models/weekly_data.dart';
// values
import '../values/months.dart';
import '../values/weekdays.dart';
class WeeklyStatisticsGraph extends StatelessWidget {
final WeeklyData weeklyData;
WeeklyStatisticsGraph(this.weeklyData);
@override
Widget build(BuildContext context) {
List<Widget> bars = [];
int max = 0;
int maxH = 150;
Map<String,dynamic> intakes = weeklyData.amounts;
for(int i=1;i<=7;i++){
if(intakes[i.toString()]>max){
max = intakes[i.toString()];
}
}
for(int i=1;i<=7;i++){
double h = max==0 ? 0 : maxH*(intakes[i.toString()]/max);
bars.add(
Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 8,height: h,
decoration: BoxDecoration(
color: Color.fromARGB(255, 0, 140, 238),
borderRadius: BorderRadius.circular(4)
),
),
SizedBox(height: 5,),
Text(
weekdays[i],
style: GoogleFonts.poppins(
color: Colors.black.withOpacity(0.5),
fontSize: 12,
fontWeight: FontWeight.w400
),
)
],
),
);
}
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)
),
child: Container(
width: 300,
height: 270,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8)
),
child: Column(
children: [
Expanded(
child: Container(
alignment: Alignment.bottomCenter,
width: 300,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: bars,
)
),
),
Padding(
padding: const EdgeInsets.fromLTRB(25, 10, 25, 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 3,
height: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.blue[300],
Colors.red[200]
]
)
),
),
SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Hydration',
style: GoogleFonts.poppins(
color: Colors.black.withOpacity(0.5),
fontSize: 12,
),
),
SizedBox(height: 5,),
Text(
'${weeklyData.percentThisWeek()} %',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w500
),
)
],
),
],
),
SizedBox(width: 20,),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 3,
height: 32,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.blue[300],
Colors.blue[100]
]
)
),
),
SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Intake',
style: GoogleFonts.poppins(
color: Colors.black.withOpacity(0.5),
fontSize: 12
),
),
SizedBox(height: 5,),
Text(
'${(weeklyData.totalThisWeek()/1000).toStringAsFixed(1)} L',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w500
),
)
],
),
],
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Week ${weeklyData.week}',
style: GoogleFonts.poppins(
color: Colors.black.withOpacity(0.5),
fontSize: 14
),
),
Text(
'${months[weeklyData.month]}, ${weeklyData.year.toString()}',
style: GoogleFonts.poppins(
color: Colors.black.withOpacity(0.5),
fontSize: 14
),
),
],
)
],
),
)
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/daily_amout_dial.dart | import 'package:flutter/material.dart';
import 'dart:math';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
// providers
import '../providers/home_provider.dart';
class DailyAmountDial extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<HomeProvider>(
builder: (context, provider, child) {
return Stack(
alignment: Alignment.center,
children: [
Transform.rotate(
angle: -pi/2,
child: Container(
width: 170,
height: 170,
child: CustomPaint(
painter: DialPainter(provider.targetReached),
),
),
),
provider.leftAmount<=0 ? Text(
'Goal Reached',
style: GoogleFonts.poppins(fontSize: 16,fontWeight: FontWeight.w500,color: Colors.white,)
):RichText(
textAlign: TextAlign.center,
text: TextSpan(
children: [
TextSpan(
text: provider.leftAmount<1000? '${provider.leftAmount} mL': '${(provider.leftAmount/1000).toStringAsFixed(1)} L' ,
style: GoogleFonts.poppins(fontSize: 30,fontWeight: FontWeight.w600)
),
TextSpan(text:'\n'),
TextSpan(
text: 'left to drink',
style: GoogleFonts.poppins(fontSize: 12,fontWeight: FontWeight.w300)
),
]
),
)
],
);
},
);
}
}
class DialPainter extends CustomPainter{
double percent;
DialPainter(this.percent);
@override
void paint(Canvas canvas, Size size) {
Offset center = Offset(size.height/2,size.width/2);
double fullRadius = (size.height/2);
Paint circle = Paint()..color=Colors.white.withOpacity(0.2)..strokeWidth=6..style=PaintingStyle.stroke;
Paint arc = Paint()..color = Colors.white..strokeCap=StrokeCap.round..style=PaintingStyle.stroke..strokeWidth=10;
canvas.drawCircle(Offset(size.width/2,size.height/2), fullRadius-2,circle);
canvas..drawArc(Rect.fromCircle(center: center,radius: fullRadius-2), 0, 2*pi*percent, false, arc);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/widgets/custom_app_bar.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class CustomAppBar extends StatelessWidget {
final Function openDrawer;
final Widget trailing;
CustomAppBar({this.openDrawer,this.trailing});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MenuButton(openDrawer),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset('assets/icons/logo.png',height: 20,),
SizedBox(width: 12,),
//Text('Drinkable',style: GoogleFonts.poppins(fontWeight: FontWeight.w600,fontSize: 17),)
Text(
'drinkable',
style: GoogleFonts.pacifico(
fontWeight: FontWeight.w500,
fontSize: 18,
color: Color.fromARGB(255, 0, 60, 192),
),
)
],
),
trailing==null ? CircleAvatar(radius: 19,backgroundColor: Colors.transparent,) : trailing
],
),
);
}
}
class MenuButton extends StatelessWidget {
final Function onTap;
MenuButton(this.onTap);
@override
Widget build(BuildContext context) {
return InkWell(
borderRadius: BorderRadius.circular(4),
onTap: onTap,
child: Container(
width: 40,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey[300],
width: 1.1,
),
borderRadius: BorderRadius.circular(4)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 11,
height: 2,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(2)
),
),
SizedBox(height: 4,),
Container(
width: 16,
height: 2,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(2)
),
),
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/models/weekly_data.dart | // utils
import '../utils/get_week.dart';
class WeeklyData {
String id;
int year;
int month;
int week;
Map<String,dynamic> amounts;
int dailyTarget;
WeeklyData({
this.id,this.year,this.month,this.week,this.amounts,this.dailyTarget
});
factory WeeklyData.fromDoc(Map<String,dynamic> doc){
Map<String,dynamic> rawAmounts = doc.containsKey('amounts') ? doc['amounts'] : {};
for(int i=1;i<=7;i++){
if(!rawAmounts.containsKey(i.toString())){
rawAmounts[i.toString()] = 0;
}
}
return WeeklyData(
id: doc['id'],
year: doc['year'],
month: doc['month'],
week: doc['week'],
amounts: rawAmounts,
dailyTarget: doc['daily_target']
);
}
Map<String,dynamic> createNewWeek(String id,int year,int month,int week,int target){
return {
'id' : id,
'year' : year,
'month' : month,
'week' : week,
'daily_target' : target
};
}
double totalThisWeek(){
double total = 0;
amounts.forEach((key, value) {
total+=value;
});
return total;
}
int percentThisWeek(){
DateTime today = DateTime.now();
int thisWeek = getWeek(today);
double max;
if(thisWeek==this.week && today.year==this.year){
max = (dailyTarget*DateTime.now().weekday).toDouble();
}else{
max = (dailyTarget*7).toDouble();
}
double total = totalThisWeek();
return ((total/max)*100).toInt();
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/models/app_user.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class AppUser {
String uid;
String googleId;
String email;
String name;
String gender;
DateTime birthday;
double weight;
TimeOfDay wakeUpTime;
int dailyTarget;
AppUser({
this.uid,
this.googleId,
this.email,
this.name,
this.gender,
this.birthday,
this.weight,
this.wakeUpTime,
this.dailyTarget
});
factory AppUser.fromDoc(Map<String,dynamic> doc){
return AppUser(
uid: doc['uid'],
googleId: doc['google_id'],
email: doc['email'],
name: doc['name'],
gender: doc['gender'],
birthday: (doc['birthday'] as Timestamp).toDate(),
weight: doc['weight'],
wakeUpTime: TimeOfDay(
hour: doc['wake_up_time']['hour'],
minute: doc['wake_up_time']['minute']
),
dailyTarget: doc['daily_target']
);
}
toDoc(){
return {
'uid' : this.uid,
'google_id' : this.googleId,
'email' : this.email,
'name' : this.name,
'gender' : this.gender,
'birthday' : Timestamp.fromDate(this.birthday),
'weight' : this.weight,
'wake_up_time' : {
'hour' : this.wakeUpTime.hour,
'minute' : this.wakeUpTime.minute
},
'daily_target' : dailyTarget
};
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/values/weather_icons.dart | Map<String,String> weatherIcons = <String,String>{
'01' : 'assets/icons/01.png',
'02' : 'assets/icons/02.png',
'03' : 'assets/icons/03.png',
'04' : 'assets/icons/04.png',
'09' : 'assets/icons/09.png',
'10' : 'assets/icons/10.png',
'11' : 'assets/icons/11.png',
'13' : 'assets/icons/13.png',
'50' : 'assets/icons/50.png',
}; | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/values/weekdays.dart | Map<int,String> weekdays = {
DateTime.monday : 'Mon',
DateTime.tuesday : 'Tue',
DateTime.wednesday : 'Wed',
DateTime.thursday : 'Thu',
DateTime.friday : 'Fri',
DateTime.saturday : 'Sat',
DateTime.sunday : 'Sun',
};
// Map<int,String> weekdays = {
// DateTime.monday : 'Monday',
// DateTime.tuesday : 'Tuesday',
// DateTime.wednesday : 'Wednesday',
// DateTime.thursday : 'Thursday',
// DateTime.friday : 'Friday',
// DateTime.saturday : 'Saturday',
// DateTime.sunday : 'Sunday',
// }; | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/values/months.dart | Map<int,String> months = {
DateTime.january : 'Jan',
DateTime.february : 'Feb',
DateTime.march : 'Mar',
DateTime.april : 'Apr',
DateTime.may : 'May',
DateTime.june : 'Jun',
DateTime.july : 'Jul',
DateTime.august : 'Aug',
DateTime.september : 'Sep',
DateTime.october : 'Oct',
DateTime.november : 'Nov',
DateTime.december : 'Dec',
}; | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/utils/get_week.dart | int getWeek(DateTime date){
int year = date.year;
DateTime stateDate = DateTime(year,1,1);
int weekday = stateDate.weekday;
int days = date.difference(stateDate).inDays;
int week = ((weekday+days)/7).ceil();
return week;
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/utils/time_converter.dart | import 'package:flutter/material.dart';
String timeConverter(TimeOfDay time) {
int hour = time.hourOfPeriod == 0 ? 12 : time.hourOfPeriod;
int min = time.minute;
DayPeriod period = time.period;
String formatedTime = '';
if(hour<10){
formatedTime += '0$hour:';
}else{
formatedTime += '$hour:';
}
if(min<9){
formatedTime += '0$min ';
}else{
formatedTime += '$min ';
}
if(period==DayPeriod.am){
formatedTime += 'AM';
}else{
formatedTime += 'PM';
}
return formatedTime;
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/utils/notification_utils.dart | import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:typed_data';
NotificationDetails getNotificationDetails(){
AndroidNotificationDetails android = AndroidNotificationDetails(
'channel_id',
'channel_name',
'channel_description',
visibility: NotificationVisibility.Public,
priority: Priority.Max,
importance: Importance.Max,
ledColor: const Color.fromARGB(255,0, 200, 255),
ledOffMs: 500,
ledOnMs: 300,
enableLights: true,
color: Colors.blue,
additionalFlags: Int32List.fromList([8]),
category: 'reminder',
playSound: true,
sound: RawResourceAndroidNotificationSound('notification_sound'),
enableVibration: true,
vibrationPattern: Int64List.fromList([0,1000,1000,1000]),
);
IOSNotificationDetails ios = IOSNotificationDetails();
NotificationDetails details = NotificationDetails(android, ios);
return details;
}
Future<void> setDailyStartNotification(TimeOfDay time, String user)async{
try{
FlutterLocalNotificationsPlugin plugin = FlutterLocalNotificationsPlugin();
NotificationDetails notificationDetails = getNotificationDetails();
await plugin.cancel(0);
await plugin.showDailyAtTime(
0,
"Good morning, $user",
"Don't forget to dring enough water today",
Time(time.hour,time.minute),
notificationDetails
);
}catch(e){
print(e);
}
}
Future<void> waterNotification(int left)async {
try{
FlutterLocalNotificationsPlugin plugin = FlutterLocalNotificationsPlugin();
NotificationDetails notificationDetails = getNotificationDetails();
await plugin.cancel(1);
await plugin.schedule(
1,
"Hey, it's time to drink water",
"$left mL water left to drink today",
DateTime.now().add(Duration(hours: 1,minutes: 30)),
notificationDetails
);
}catch(e){
print(e);
}
}
Future<void> cancelAllNotifications() async{
try{
FlutterLocalNotificationsPlugin plugin = FlutterLocalNotificationsPlugin();
await plugin.cancelAll();
}catch(e){
print(e);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/screens/profile_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:intl/intl.dart';
import 'package:google_fonts/google_fonts.dart';
// providers
import '../providers/auth_provider.dart';
import '../providers/home_provider.dart';
// models
import '../models/app_user.dart';
// widgets
import '../widgets/custom_app_bar.dart';
import '../widgets/custom_form_field.dart';
import '../widgets/custom_progress_indicator.dart';
// utils
import '../utils/time_converter.dart';
class ProfileScreen extends StatelessWidget {
final Function openDrawer;
ProfileScreen({
this.openDrawer
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.only(top: 30),
child: SingleChildScrollView(
child: Column(
children: [
CustomAppBar(openDrawer: openDrawer),
Consumer<HomeProvider>(
builder: (context, homeProvider, child) {
AppUser appUser = homeProvider.appUser;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 30,vertical: 20),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
appUser.name,
style: GoogleFonts.poppins(
fontSize: 19,
fontWeight: FontWeight.w500
),
),
SizedBox(height: 5,),
Text(
appUser.email,
style: GoogleFonts.poppins(
fontSize: 14,
),
)
],
),
Consumer<AuthProvider>(
builder: (context, authProvider, child) {
User user = authProvider.user;
return CircleAvatar(
radius: 35,
backgroundImage: NetworkImage(user.photoURL),
);
},
),
],
),
SizedBox(height: 50,),
DataEntryForm(appUser)
],
),
);
},
)
],
),
),
),
);
}
}
class DataEntryForm extends StatefulWidget {
final AppUser appUser;
DataEntryForm(this.appUser);
@override
_DataEntryFormState createState() => _DataEntryFormState();
}
class _DataEntryFormState extends State<DataEntryForm> {
TextEditingController _textEditingController;
AppUser _appUser;
bool _loading = false;
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
_appUser = AppUser.fromDoc(widget.appUser.toDoc());
_textEditingController = TextEditingController(text: _appUser.dailyTarget.toString());
}
void toggleLoading(){
setState(() {
_loading = !_loading;
});
}
void submit()async{
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
toggleLoading();
try{
await Provider.of<HomeProvider>(context,listen: false).updateUser(_appUser);
}catch(e){
print(e);
}
toggleLoading();
}
void setWater({double weight}){
if(_appUser.weight!=null || weight!=null){
double calWater = weight!=null ? weight*2.205 : _appUser.weight*2.205;
calWater = calWater/2.2;
int age = DateTime.now().year-_appUser.birthday.year;
if(age<30){
calWater = calWater*40;
}else if(age>=30 && age<=55){
calWater = calWater*35;
}else{
calWater = calWater*30;
}
calWater = calWater/28.3;
calWater = calWater*29.574;
setState(() {
_appUser.dailyTarget= calWater.toInt();
_appUser.weight = weight==null? _appUser.weight : weight;
_textEditingController.text = _appUser.dailyTarget.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
flex: 47,
child: CustomFormField(
label: 'Gender',
child: DropdownButtonFormField<String>(
value: _appUser.gender,
items: <DropdownMenuItem<String>>[
DropdownMenuItem(
child: Text('Male',style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),),
value: 'male',
),
DropdownMenuItem(
child: Text('Female',style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),),
value: 'female',
),
],
decoration: InputDecoration(
border: InputBorder.none
),
onChanged: (String gender){
setState(() {
_appUser.gender = gender;
});
},
),
)
),
Expanded(
flex: 6,
child: SizedBox(width: 20,)
),
Expanded(
flex: 47,
child: GestureDetector(
onTap: ()async{
DateTime date = await showDatePicker(
context: context,
initialDate:_appUser.birthday,
firstDate: DateTime(1960),
lastDate: DateTime(DateTime.now().year-12,12,31),
);
if(date!=null){
setState(() {
_appUser.birthday = date;
});
setWater();
}
},
child: CustomFormField(
label: 'Birthday',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
DateFormat.yMMMd('en_US').format(_appUser.birthday),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
),
Icon(Icons.arrow_drop_down)
],
)
),
)
),
],
),
SizedBox(height: 15,),
Row(
children: [
Expanded(
flex: 47,
child: CustomFormField(
label: 'Weight',
child: TextFormField(
initialValue: _appUser.weight.toString(),
decoration: InputDecoration(
border: InputBorder.none,
hintText: '60 kg',
suffixText: 'kg',
),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
validator: (String value){
if(value.isEmpty){
return 'Enter weight';
}
if(double.parse(value)<40){
return 'You are underweight';
}
return null;
},
onChanged: (String value){
setWater(weight: double.parse(value));
},
),
)
),
Expanded(
flex: 6,
child: SizedBox(width: 20,),
),
Expanded(
flex: 47,
child: GestureDetector(
onTap: ()async{
TimeOfDay time = await showTimePicker(
context: context,
initialTime: TimeOfDay(hour: 8, minute: 0),
);
if(time!=null){
setState(() {
_appUser.wakeUpTime = time;
});
}
},
child: CustomFormField(
label: 'Wakes Up',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
timeConverter(_appUser.wakeUpTime),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
),
Icon(Icons.arrow_drop_down)
],
)
),
)
),
],
),
SizedBox(height: 15,),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Expanded(
flex: 2,
child: CustomFormField(
label: 'Water',
child: TextFormField(
controller: _textEditingController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: '3200 mL',
suffixText: 'mL',
),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
validator: (String value){
if(value.isEmpty){
return 'Enter water amount';
}
if(double.parse(value)<1600){
return 'Less than min water';
}
return null;
},
onChanged: (String value){
setState(() {
_appUser.dailyTarget = int.parse(value);
});
},
),
)
),
Expanded(
child: SizedBox(width: 0,),
),
RaisedButton(
elevation: 1,
color: Color.fromARGB(255, 0, 60, 192),
child: _loading ? SizedBox(
height: 22,width: 22,
child: CustomProgressIndicatior()
) : Text(
'Update',
style: GoogleFonts.poppins(
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 12
),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3)),
onPressed: (){
//toggleLoading();
submit();
},
)
],
)
],
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/screens/data_entry_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:intl/intl.dart';
import 'package:google_fonts/google_fonts.dart';
// providers
import '../providers/auth_provider.dart';
// utils
import '../utils/time_converter.dart';
// widgets
import '../widgets/custom_form_field.dart';
import '../widgets/custom_progress_indicator.dart';
class DataEntryScreen extends StatelessWidget {
static const routeName = 'data-entry-screen';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.fromLTRB(30,30, 30, 0),
child: SingleChildScrollView(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
InkWell(
onTap: (){
Navigator.of(context).pop();
},
child: Icon(Icons.arrow_back_ios)
)
],
),
SizedBox(height: 20,),
Column(
children: [
Icon(Icons.date_range),
SizedBox(height: 10,),
Text('About you',style: GoogleFonts.poppins(fontSize: 22,fontWeight: FontWeight.w500),),
SizedBox(height: 20,),
Container(
constraints: BoxConstraints(
maxWidth: 270
),
child: Text(
'This information will let us help to calculate your daily recommended water intake amount and remind you to drink water in intervals.',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.black.withOpacity(0.60),
height: 1.4,
fontWeight: FontWeight.w400
),
),
),
SizedBox(height: 30,),
Consumer<AuthProvider>(
builder: (context, authProvider, child) {
GoogleSignInAccount googleAccount = authProvider.googleAcount;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
backgroundImage: NetworkImage(googleAccount.photoUrl),
),
SizedBox(height: 15,),
Text(
'${googleAccount.email}',
style: GoogleFonts.poppins(
fontSize: 13
),
),
],
);
},
),
],
),
SizedBox(height: 50,),
DataEntryForm(),
],
),
),
),
);
}
}
class DataEntryForm extends StatefulWidget {
@override
_DataEntryFormState createState() => _DataEntryFormState();
}
class _DataEntryFormState extends State<DataEntryForm> {
bool _loading = false;
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void toggleLoading(){
setState(() {
_loading = !_loading;
});
}
// data
String _gender = 'male';
DateTime _birthday = DateTime(1997,4,1);
double _weight;
TimeOfDay _wakeUpTime = TimeOfDay(hour: 8, minute: 0);
int _water = 3200;
void submit()async{
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
toggleLoading();
try{
await Provider.of<AuthProvider>(context,listen: false).signUp(
_gender,
_birthday,
_weight,
_wakeUpTime,
_water
);
Navigator.of(context).pop();
return;
}catch(e){
print(e);
}
toggleLoading();
}
void setWater({double weight}){
if(_weight!=null || weight!=null){
double calWater = weight!=null ? weight*2.205 : _weight*2.205;
calWater = calWater/2.2;
int age = DateTime.now().year-_birthday.year;
if(age<30){
calWater = calWater*40;
}else if(age>=30 && age<=55){
calWater = calWater*35;
}else{
calWater = calWater*30;
}
calWater = calWater/28.3;
calWater = calWater*29.574;
setState(() {
_water = calWater.toInt();
_weight = weight==null? _weight : weight;
});
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
flex: 47,
child: CustomFormField(
label: 'Gender',
child: DropdownButtonFormField<String>(
value: _gender,
items: <DropdownMenuItem<String>>[
DropdownMenuItem(
child: Text('Male',style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),),
value: 'male',
),
DropdownMenuItem(
child: Text('Female',style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),),
value: 'female',
),
],
decoration: InputDecoration(
border: InputBorder.none
),
onChanged: (String gender){
setState(() {
_gender = gender;
});
},
),
)
),
Expanded(
flex: 6,
child: SizedBox(width: 20,)
),
Expanded(
flex: 47,
child: GestureDetector(
onTap: ()async{
DateTime date = await showDatePicker(
context: context,
initialDate:DateTime(1997,4,1),
firstDate: DateTime(1960),
lastDate: DateTime(DateTime.now().year-12,12,31),
);
if(date!=null){
setState(() {
_birthday = date;
});
setWater();
}
},
child: CustomFormField(
label: 'Birthday',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
DateFormat.yMMMd('en_US').format(_birthday),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
),
Icon(Icons.arrow_drop_down)
],
)
),
)
),
],
),
SizedBox(height: 15,),
Row(
children: [
Expanded(
flex: 47,
child: CustomFormField(
label: 'Weight',
child: TextFormField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: '60 kg',
suffixText: 'kg',
),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
validator: (String value){
if(value.isEmpty){
return 'Enter weight';
}
if(double.parse(value)<40){
return 'You are underweight';
}
return null;
},
onChanged: (String value){
setWater(weight: double.parse(value));
},
),
)
),
Expanded(
flex: 6,
child: SizedBox(width: 20,),
),
Expanded(
flex: 47,
child: GestureDetector(
onTap: ()async{
TimeOfDay time = await showTimePicker(
context: context,
initialTime: TimeOfDay(hour: 8, minute: 0),
);
if(time!=null){
setState(() {
_wakeUpTime = time;
});
}
},
child: CustomFormField(
label: 'Wakes Up',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
timeConverter(_wakeUpTime),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
),
Icon(Icons.arrow_drop_down)
],
)
),
)
),
],
),
SizedBox(height: 15,),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Expanded(
flex: 2,
child: CustomFormField(
label: 'Water',
child: TextFormField(
controller: TextEditingController(text: '$_water'),
decoration: InputDecoration(
border: InputBorder.none,
hintText: '3200 mL',
suffixText: 'mL',
),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
validator: (String value){
if(value.isEmpty){
return 'Enter water amount';
}
if(double.parse(value)<1600){
return 'Less than min water';
}
return null;
},
onSaved: (String value){
setState(() {
_water = int.parse(value);
});
},
),
)
),
Expanded(
child: SizedBox(width: 0,),
),
RaisedButton(
elevation: 1,
color: Color.fromARGB(255, 0, 60, 192),
child: _loading ? SizedBox(
height: 22,width: 22,
child: CustomProgressIndicatior()
) : Text(
'Let\'t go',
style: GoogleFonts.poppins(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 13
),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(3)),
onPressed: (){
//toggleLoading();
submit();
},
)
],
)
],
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/screens/scatistics_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_fonts/google_fonts.dart';
// providers
import '../providers/auth_provider.dart';
import '../providers/statistics_provider.dart';
// models
import '../models/weekly_data.dart';
// widgets
import '../widgets/custom_app_bar.dart';
import '../widgets/weekly_statistics_graph.dart';
import '../widgets/custom_progress_indicator.dart';
import '../widgets/three_layer_background.dart';
class StatisticsScreen extends StatefulWidget {
final Function openDrawer;
StatisticsScreen({
this.openDrawer
});
@override
_StatisticsScreenState createState() => _StatisticsScreenState();
}
class _StatisticsScreenState extends State<StatisticsScreen> {
bool _loading = false;
@override
void initState() {
super.initState();
init();
}
void toggleLoading(){
setState(() {
_loading = !_loading;
});
}
void init() async {
toggleLoading();
await Provider.of<StatisticsProvider>(context,listen: false).init();
toggleLoading();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.only(top: 30),
child: _loading ? Center(child: CustomProgressIndicatior(),) : Column(
children: [
CustomAppBar(
openDrawer: widget.openDrawer,
trailing: Consumer<AuthProvider>(
builder: (context, authProvider, child) {
User user = authProvider.user;
return CircleAvatar(
radius: 19,
backgroundImage: NetworkImage(user.photoURL),
);
},
),
),
Container(
padding: EdgeInsets.fromLTRB(30, 25, 30, 30),
alignment: Alignment.centerLeft,
child: Text(
'Statistics',
textAlign: TextAlign.left,
style: GoogleFonts.poppins(
color: Color.fromARGB(255, 0, 60, 192),
fontSize: 25,
letterSpacing: 1,
fontWeight: FontWeight.w500
),
),
),
//SizedBox(height: 30,),
Expanded(
child: Stack(
children: [
ThreeLayerBackground(),
Consumer<StatisticsProvider>(
builder: (context, statisticsProvider, child) {
List<WeeklyData> weeklyData = statisticsProvider.weeklyData;
return ListView.separated(
padding: EdgeInsets.fromLTRB(30, 40, 30, 40),
itemCount: weeklyData.length,
itemBuilder: (context, index) {
return WeeklyStatisticsGraph(weeklyData[index]);
},
separatorBuilder: (context, index) {
return SizedBox(height: 20,);
},
);
},
),
],
),
)
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/screens/home_screen.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
// widgets
import '../widgets/custom_app_bar.dart';
import '../widgets/goal_and_add.dart';
import '../widgets/weather_suggestion.dart';
import '../widgets/loading_screen.dart';
// providers
import '../providers/home_provider.dart';
import '../providers/auth_provider.dart';
// models
import '../models/app_user.dart';
// widgets
import '../widgets/custom_progress_indicator.dart';
import '../widgets/custom_form_field.dart';
class HomeScreen extends StatefulWidget {
final Function openDrawer;
HomeScreen({
this.openDrawer
});
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _isLoading = false;
@override
void initState() {
super.initState();
init();
}
void toggleLoading(){
setState(() {
_isLoading = !_isLoading;
});
}
void init() async {
toggleLoading();
await Provider.of<HomeProvider>(context,listen: false).init();
toggleLoading();
}
@override
Widget build(BuildContext context) {
return _isLoading ? LoadingScreen() : Scaffold(
body: Container(
padding: EdgeInsets.only(top: 30),
child: SingleChildScrollView(
child: Column(
children: [
CustomAppBar(
openDrawer: widget.openDrawer,
trailing: Consumer<AuthProvider>(
builder: (context, authProvider, child) {
User user = authProvider.user;
return CircleAvatar(
radius: 19,
backgroundImage: NetworkImage(user.photoURL),
);
},
),
),
SizedBox(height: 40,),
GoalAndAdd(),
SizedBox(height: 15,),
Padding(
padding: const EdgeInsets.fromLTRB(30,0,30,20),
child: WeatherSuggestion()
)
],
),
),
),
floatingActionButton: FloatingActionButton(
elevation: 3,
backgroundColor: Color.fromARGB(255, 0, 60, 192),
child: Icon(Icons.add,size: 30,),
onPressed: (){
//Navigator.of(context).pushNamed(AddWaterScreen.routeName);
showDialog(
context: context,
builder: (BuildContext ctx){
return AddWaterWidget();
}
);
}
),
);
}
}
class AddWaterWidget extends StatefulWidget {
@override
_AddWaterWidgetState createState() => _AddWaterWidgetState();
}
class _AddWaterWidgetState extends State<AddWaterWidget> {
bool _loading = false;
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
// data
DateTime _time = DateTime.now();
int _water;
void toggleLoading(){
setState(() {
_loading = !_loading;
});
}
void submit()async{
if(!_formKey.currentState.validate()){
return;
}
_formKey.currentState.save();
toggleLoading();
try{
await Provider.of<HomeProvider>(context,listen: false).addWater(_water,_time);
Navigator.of(context).pop();
return;
}catch(e){
print(e);
}
toggleLoading();
}
@override
Widget build(BuildContext context) {
AppUser appUser = Provider.of<HomeProvider>(context).appUser;
return AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(height: 15,),
Text('Add Water',
style: GoogleFonts.poppins(
fontSize: 14
),
),
SizedBox(height: 20,),
Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
GestureDetector(
onTap: ()async{
DateTime date = await showDatePicker(
context: context,
initialDate:_time,
firstDate: DateTime(1960),
lastDate: _time,
);
if(date!=null && date.isBefore(DateTime.now())){
setState(() {
_time = date;
});
}
},
child: CustomFormField(
label: 'Date',
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
DateFormat.yMMMd('en_US').format(_time),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
),
Icon(Icons.arrow_drop_down)
],
)
),
),
SizedBox(height: 10,),
CustomFormField(
label: 'Water',
child: TextFormField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: '240 mL',
suffixText: 'mL',
),
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w500
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
validator: (String value){
if(value.isEmpty){
return 'Enter water amount';
}
if(double.parse(value)<=0){
return 'Wrong value';
}
if(double.parse(value)>appUser.dailyTarget){
return 'Daily limit exceed';
}
return null;
},
onSaved: (String value){
setState(() {
_water = int.parse(value);
});
},
),
),
],
),
)
],
),
contentPadding: EdgeInsets.symmetric(horizontal: 15,vertical: 5),
actions: <Widget>[
FlatButton(
textColor: Color.fromARGB(255, 0, 60, 192),
child: Text('Cancel',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w500
)
),
onPressed: (){
Navigator.of(context).pop();
},
),
FlatButton(
color: Color.fromARGB(255, 0, 60, 192),
child: _loading ? SizedBox(
height: 22,width: 22,
child: CustomProgressIndicatior()
) : Text('Add',
style: GoogleFonts.poppins(
fontSize: 13,
fontWeight: FontWeight.w500
)
),
onPressed: submit,
),
],
);
}
}
| 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/screens/auth_screen.dart | import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:provider/provider.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter/services.dart';
// providers
import '../providers/auth_provider.dart';
// screens
import '../screens/data_entry_screen.dart';
// widgets
import '../widgets/custom_progress_indicator.dart';
class AuthScreen extends StatefulWidget {
static const routeName = 'auth-screen';
@override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
bool _loading = false;
@override
void initState() {
super.initState();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark,
));
}
void toggleLoading(){
setState(() {
_loading = !_loading;
});
}
void selectAccount(BuildContext ctx) async {
toggleLoading();
bool newuser = await Provider.of<AuthProvider>(ctx,listen: false).selectGoogleAcount();
if(!newuser){
await Provider.of<AuthProvider>(ctx,listen: false).signIn();
}else{
toggleLoading();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.fromLTRB(30, 0, 30, 30),
child: Column(
children: [
Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset('assets/images/big_logo.png',height: 90,),
SizedBox(height: 10,),
Text(
'drinkable',
style: GoogleFonts.pacifico(
fontWeight: FontWeight.w500,
fontSize: 26,
color: Color.fromARGB(255, 0, 60, 192),
),
),
SizedBox(height: 15,),
Container(
constraints: BoxConstraints(
maxWidth: 250
),
child: Text(
'Drinkable keeps track your daily water intake and reminds you to drink water by sending notification in intervals',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 14,
color: Colors.black.withOpacity(0.60)
)
),
),
],
),
),
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
_loading ? CustomProgressIndicatior() : Consumer<AuthProvider>(
builder: (ctx, authProvider, child) {
GoogleSignInAccount googleAccount = authProvider.googleAcount;
return googleAccount!=null ?
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
CircleAvatar(
backgroundImage: NetworkImage(googleAccount.photoUrl),
),
FlatButton(
child: Text('Continue as ${googleAccount.displayName}'),
onPressed: (){
Navigator.of(context).pushNamed(DataEntryScreen.routeName);
},
),
InkWell(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: (){
Provider.of<AuthProvider>(ctx,listen: false).clearGoogleAccount();
},
child: Padding(
padding: EdgeInsets.fromLTRB(10, 10, 0, 10),
child: Icon(Icons.clear),
),
),
],
) : GestureDetector(
onTap: (){
selectAccount(context);
},
child: Card(
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
color: Colors.blueAccent,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
padding: EdgeInsets.all(3),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8)
),
child: Image.asset('assets/icons/google.png',height: 20,)
),
Text(
'Continue with Google',
style:GoogleFonts.poppins(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500
),
)
],
),
),
),
);
},
),
Container(
padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 11
),
children: [
TextSpan(
text: 'By signing up you accept the ',
),
TextSpan(
text: 'Terms of Service and Privacy Policy.',
style: GoogleFonts.poppins(
fontWeight: FontWeight.w500
)
)
]
),
)
)
],
)
],
),
),
);
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/providers/statistics_provider.dart | import 'package:flutter/foundation.dart';
import '../models/weekly_data.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class StatisticsProvider extends ChangeNotifier {
FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
String _uid;
CollectionReference _weeksRef;
List<WeeklyData> _weeklyData = [];
List<WeeklyData> get weeklyData => [..._weeklyData];
void update(User user){
if(user!=null){
_uid = user.uid;
_weeksRef = _firebaseFirestore.collection('users').doc(_uid).collection('weeks');
}else{
_uid = null;
_weeksRef = null;
_weeklyData.clear();
}
}
Future<void> init() async {
try {
_weeklyData.clear();
QuerySnapshot snapshot = await _weeksRef.orderBy('id',descending: true).limit(4).get();
List<QueryDocumentSnapshot> docsSnap = snapshot.docs;
docsSnap.forEach((docSnap) {
_weeklyData.add(new WeeklyData.fromDoc(docSnap.data()));
});
}catch(e){
print(e);
}
}
} | 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/providers/home_provider.dart | import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:location/location.dart';
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
// utils
import '../utils/get_week.dart';
import '../utils/notification_utils.dart';
//values
import '../values/api_key.dart';
// models
import '../models/weekly_data.dart';
import '../models/app_user.dart';
class HomeProvider extends ChangeNotifier {
FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
Location _location = Location();
bool _isInited = false;
DateTime _today = DateTime.now();
WeeklyData _weeklyData;
String _uid;
AppUser _appUser;
CollectionReference _weekColRef;
DocumentReference _userRef;
DocumentReference _currentWeek;
Map<String,dynamic> _weather;
LocationData _locationData;
void update(User user){
if(user!=null){
_uid = user.uid;
_weekColRef = _firebaseFirestore.collection('users').doc(_uid).collection('weeks');
_userRef = _firebaseFirestore.collection('users').doc(_uid);
}else{
_isInited = false;
_uid = null;
_weeklyData = null;
_appUser = null;
_weekColRef = null;
_userRef = null;
_currentWeek = null;
_weather = null;
_locationData = null;
}
notifyListeners();
}
Map<String,dynamic> get weather => _weather;
AppUser get appUser => _appUser;
String get dailyTarget {
int target = _appUser.dailyTarget;
if(target<1000){
return '$target mL';
}else{
return '${(target/1000).toStringAsFixed(1)} L';
}
}
int get leftAmount {
int target = _appUser.dailyTarget;
int consumed = _weeklyData.amounts[_today.weekday.toString()].toInt();
int left = target-consumed;
return left;
}
double get targetReached {
int target = _appUser.dailyTarget;
int consumed = _weeklyData.amounts[_today.weekday.toString()].toInt();
return consumed/target;
}
Future<void> init()async{
if(_isInited==false){
try {
int week = getWeek(_today);
String docId = '${_today.year}_$week';
_currentWeek = _weekColRef.doc(docId);
DocumentSnapshot userSnapshot = await _userRef.get();
_appUser = AppUser.fromDoc(userSnapshot.data());
DocumentSnapshot snapshot = await _currentWeek.get();
if(!snapshot.exists){
Map<String,dynamic> newWeek = WeeklyData().createNewWeek(docId,_today.year,_today.month,week,_appUser.dailyTarget);
await _currentWeek.set(newWeek);
_weeklyData = WeeklyData.fromDoc(newWeek);
}else{
_weeklyData = WeeklyData.fromDoc(snapshot.data());
}
_isInited = true;
bool canGetLocation = await getLocationService();
if(canGetLocation){
_locationData = await _location.getLocation();
http.Response response = await http.get(
'https://api.openweathermap.org/data/2.5/weather?lat=${_locationData.latitude}&lon=${_locationData.longitude}&appid=${keys['openweather']}&units=metric'
);
if(response.statusCode==200){
final weatherInfo = jsonDecode(response.body);
_weather = weatherInfo['weather'][0];
}
}
notifyListeners();
}catch(e){
print(e);
}
}else{
print('Data already inited');
}
}
Future<void> addWater(int amount,DateTime time) async {
try{
int weekday = time.weekday;
int week = getWeek(time);
String weekId = '${time.year}_$week';
await _firebaseFirestore.runTransaction((transaction)async{
DocumentReference weekDocRef = _firebaseFirestore.collection('users').doc(_uid).collection('weeks').doc(weekId);
DocumentReference yearDocRef = _firebaseFirestore.collection('users').doc(_uid).collection('years').doc('${time.year}');
DocumentReference monthDocRef = _firebaseFirestore.collection('users').doc(_uid).collection('months').doc('${time.year}_${time.month}');
DocumentSnapshot yearDocSnap = await transaction.get(yearDocRef);
DocumentSnapshot monthDocSnap = await transaction.get(monthDocRef);
DocumentSnapshot weekDocSnap = await transaction.get(weekDocRef);
if(!yearDocSnap.exists){
transaction.set(yearDocRef, {
'year' : time.year
},SetOptions(merge: true));
}
if(!monthDocSnap.exists){
transaction.set(monthDocRef, {
'year' : time.year,
'month' : time.month
},SetOptions(merge: true));
}
if(!weekDocSnap.exists){
transaction.set(weekDocRef, {
'daily_target' : _appUser.dailyTarget,
'year' : time.year,
'month' : time.month,
'week' : week,
'id' : weekId,
},SetOptions(merge: true));
}
transaction.update(yearDocRef, {
'amounts.${time.month}' : FieldValue.increment(amount)
});
transaction.update(monthDocRef, {
'amounts.${time.day}' : FieldValue.increment(amount)
});
transaction.update(weekDocRef, {
'amounts.$weekday' : FieldValue.increment(amount)
});
});
if(_weeklyData.id==weekId){
_weeklyData.amounts[weekday.toString()] += amount;
if(weekday==DateTime.now().weekday){
if(leftAmount>0){
await waterNotification(leftAmount);
}
}
notifyListeners();
}
}catch(e){
print(e);
}
}
Future<bool> getLocationService()async{
bool isServiceEnabled = await _location.serviceEnabled();
if(!isServiceEnabled){
bool _enabled = await _location.requestService();
if (_enabled) {
}else{
return false;
}
}
PermissionStatus permissionGranted = await _location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
PermissionStatus _isGranted = await _location.requestPermission();
if (_isGranted != PermissionStatus.granted) {
return false;
}
}
return true;
}
Future<void> updateUser(AppUser appUser)async{
try{
await _firebaseFirestore.runTransaction((transaction)async{
transaction.update(_currentWeek,{
'daily_target' : appUser.dailyTarget
});
transaction.update(_userRef, appUser.toDoc());
});
await setDailyStartNotification(appUser.wakeUpTime,appUser.name);
_appUser = appUser;
notifyListeners();
}catch(e){
print(e);
}
}
}
| 0 |
mirrored_repositories/drinkable/lib | mirrored_repositories/drinkable/lib/providers/auth_provider.dart | import 'package:flutter/foundation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
// models
import '../models/app_user.dart';
//utils
import '../utils/notification_utils.dart';
class AuthProvider extends ChangeNotifier {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
GoogleSignIn _googleSignIn = GoogleSignIn();
FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
GoogleSignInAccount get googleAcount => _googleSignIn.currentUser;
User get user => _firebaseAuth.currentUser;
Future<bool> selectGoogleAcount() async {
try {
await _googleSignIn.signOut();
GoogleSignInAccount googleAccount = await _googleSignIn.signIn();
QuerySnapshot querySnapshot = await _firestore.collection('users').where('google_id',isEqualTo: googleAccount.id).get();
List<QueryDocumentSnapshot> docs = querySnapshot.docs;
if(docs.length==0){
return true;
}
QueryDocumentSnapshot userDoc = docs[0];
Map<String,dynamic> data = userDoc.data();
TimeOfDay wakeUpTime = TimeOfDay(
hour: data['wake_up_time']['hour'],
minute: data['wake_up_time']['minute']
);
await setDailyStartNotification(wakeUpTime,data['name']);
return false;
}catch(e){
print(e);
return true;
}
}
Future<void> signIn() async {
try{
if(_googleSignIn.currentUser!=null){
GoogleSignInAuthentication _googleSignInAuthentication = await _googleSignIn.currentUser.authentication;
OAuthCredential _oAuthCredential = GoogleAuthProvider.credential(
accessToken: _googleSignInAuthentication.accessToken,
idToken: _googleSignInAuthentication.idToken
);
await _firebaseAuth.signInWithCredential(_oAuthCredential);
notifyListeners();
}
}catch(e){
print(e);
}
}
Future<void> signUp(String gender,DateTime birthday,double weight,TimeOfDay time,int water) async {
try{
await signIn();
User user = _firebaseAuth.currentUser;
DocumentReference userRef = _firestore.collection('users').doc(user.uid);
await userRef.set(AppUser(
uid: user.uid,
googleId: _googleSignIn.currentUser.id,
email: user.email,
name: user.displayName,
gender: gender,
birthday: birthday,
weight: weight,
wakeUpTime: time,
dailyTarget: water
).toDoc());
await setDailyStartNotification(time,user.displayName);
notifyListeners();
}catch(e){
print(e);
}
}
void clearGoogleAccount()async{
await _googleSignIn.signOut();
notifyListeners();
}
void signOut() async {
await cancelAllNotifications();
await _googleSignIn.signOut();
await _firebaseAuth.signOut();
notifyListeners();
}
} | 0 |
mirrored_repositories/drinkable | mirrored_repositories/drinkable/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:drinkable/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/hadeeth | mirrored_repositories/hadeeth/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hadeeth/core/dependecies/injection_container.dart' as di;
import 'package:hadeeth/core/theme/app_theme.dart';
import 'package:hadeeth/src/category/presentation/blocs/category/category_bloc.dart';
import 'package:hadeeth/src/category/presentation/blocs/category_detail/category_detail_bloc.dart';
import 'package:hadeeth/src/category/presentation/screens/categories_screen.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await di.init();
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) =>
di.sl<CategoryBloc>()..add(GetAllCategories(lang: 'ar')),
),
BlocProvider(
create: (context) => di.sl<CategoryDetailBloc>(),
),
],
child: MaterialApp(
locale: const Locale('ar'),
supportedLocales: const [
Locale('ar'),
Locale('en'),
],
theme: MyTheme.lightTheme,
darkTheme: MyTheme.darkTheme,
home: const CategoriesScreen(),
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/core | mirrored_repositories/hadeeth/lib/core/network/netwotk_info.dart | import 'package:internet_connection_checker/internet_connection_checker.dart';
abstract class NetworkInfo {
Future<bool> get isConnected;
}
class NetworkInfoImpl implements NetworkInfo {
final InternetConnectionChecker connectionChecker;
NetworkInfoImpl(this.connectionChecker);
@override
Future<bool> get isConnected => connectionChecker.hasConnection;
}
| 0 |
mirrored_repositories/hadeeth/lib/core | mirrored_repositories/hadeeth/lib/core/theme/app_theme.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class MyTheme {
static ThemeData lightTheme = ThemeData(
useMaterial3: true,
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFFA5D6A7), brightness: Brightness.light),
);
static ThemeData darkTheme = ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFFA5D6A7), brightness: Brightness.dark),
);
}
| 0 |
mirrored_repositories/hadeeth/lib/core | mirrored_repositories/hadeeth/lib/core/error/exceptions.dart | abstract class AppException implements Exception {
final String message;
AppException(this.message);
@override
String toString() => 'AppException: $message';
}
class EmptyDataException extends AppException {
EmptyDataException(String message) : super(message);
}
class ServerException extends AppException {
ServerException(String message) : super(message);
}
class OfflineException extends AppException {
OfflineException(String message) : super(message);
}
| 0 |
mirrored_repositories/hadeeth/lib/core | mirrored_repositories/hadeeth/lib/core/error/failures.dart | abstract class Failure {
String get message;
}
class EmptyDataFailure extends Failure {
@override
final String message;
EmptyDataFailure({required this.message});
@override
String toString() => 'EmptyDataFailure: $message';
}
class ServerFailure extends Failure {
@override
final String message;
ServerFailure({required this.message});
@override
String toString() => 'ServerFailure: $message';
}
class OfflineFailure extends Failure {
@override
final String message;
OfflineFailure({required this.message});
@override
String toString() => 'OfflineFailure: $message';
}
| 0 |
mirrored_repositories/hadeeth/lib/core | mirrored_repositories/hadeeth/lib/core/dependecies/injection_container.dart | import 'package:get_it/get_it.dart';
import 'package:hadeeth/core/network/netwotk_info.dart';
import 'package:hadeeth/src/category/data/data%20source/category_remote_date_source.dart';
import 'package:hadeeth/src/category/data/repository/category_repository_impl.dart';
import 'package:hadeeth/src/category/domain/repository/category_repository.dart';
import 'package:hadeeth/src/category/domain/usecases/all_categories_usecase.dart';
import 'package:hadeeth/src/category/domain/usecases/category_detail_usecase.dart';
import 'package:hadeeth/src/category/presentation/blocs/category/category_bloc.dart';
import 'package:hadeeth/src/category/presentation/blocs/category_detail/category_detail_bloc.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:http/http.dart' as http;
final sl = GetIt.instance;
Future<void> init() async {
// Core
sl.registerLazySingleton<NetworkInfo>(() => NetworkInfoImpl(sl()));
sl.registerLazySingleton(() => InternetConnectionChecker());
sl.registerLazySingleton(() => http.Client());
// Categories & CategoryDetail
// Bloc
sl.registerFactory(() => CategoryBloc(allCategoriesUsecase: sl()));
sl.registerFactory(() => CategoryDetailBloc(categoryDetailUsecase: sl()));
// Usecase
sl.registerLazySingleton(() => AllCategoriesUsecase(categoryRepo: sl()));
sl.registerLazySingleton(() => CategoryDetailUsecase(categoryRepo: sl()));
// Repository
sl.registerLazySingleton<CategoryRepository>(() => CategoryRepositoryImpl(
networkInfo: sl(), categoryRemoteDataSource: sl()));
// Data Source
sl.registerLazySingleton<CategoryRemoteDataSource>(
() => CategoryRemoteDataSourceImpl(client: sl()));
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/repository/category_repository_impl.dart | import 'package:dartz/dartz.dart';
import 'package:hadeeth/core/error/failures.dart';
import 'package:hadeeth/core/network/netwotk_info.dart';
import 'package:hadeeth/src/category/data/data%20source/category_remote_date_source.dart';
import 'package:hadeeth/src/category/domain/entities/category.dart';
import 'package:hadeeth/src/category/domain/entities/category_detail.dart';
import 'package:hadeeth/src/category/domain/repository/category_repository.dart';
class CategoryRepositoryImpl implements CategoryRepository {
final NetworkInfo networkInfo;
final CategoryRemoteDataSource categoryRemoteDataSource;
const CategoryRepositoryImpl(
{required this.networkInfo, required this.categoryRemoteDataSource});
@override
Future<Either<Failure, List<Category>>> getAllCategories(
{required String lang}) async {
if (await networkInfo.isConnected) {
try {
final categories =
await categoryRemoteDataSource.getAllCategories(lang: lang);
return Right(categories);
} catch (e) {
return Left(ServerFailure(message: ''));
}
} else {
return Left(OfflineFailure(message: 'offline'));
}
}
@override
Future<Either<Failure, CategoryDetail>> getCategoryDetail(
{required String lang,
required String categoryId,
required String page,
required String perPage}) async {
if (await networkInfo.isConnected) {
try {
final categoryDetail = await categoryRemoteDataSource.getCategoryDetail(
lang: lang, categoryId: categoryId, page: page, perPage: perPage);
return Right(categoryDetail);
} catch (e) {
return Left(ServerFailure(message: ''));
}
} else {
return Left(OfflineFailure(message: 'offline'));
}
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/data source/category_remote_date_source.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hadeeth/core/error/exceptions.dart';
import 'package:hadeeth/src/category/data/models/category_detail_model.dart';
import 'package:hadeeth/src/category/data/models/category_model.dart';
import 'package:http/http.dart' as http;
abstract class CategoryRemoteDataSource {
Future<List<CategoryModel>> getAllCategories({required String lang});
Future<CategoryDetailModel> getCategoryDetail(
{required String lang,
required String categoryId,
required String page,
required String perPage});
}
const baseUrl = 'https://hadeethenc.com';
class CategoryRemoteDataSourceImpl implements CategoryRemoteDataSource {
final http.Client client;
const CategoryRemoteDataSourceImpl({required this.client});
@override
Future<List<CategoryModel>> getAllCategories({required String lang}) async {
final url = Uri.parse('$baseUrl/api/v1/categories/list/?language=$lang');
final response = await client.get(url);
if (response.statusCode == 200) {
debugPrint('response.body: ${response.body}');
final List<dynamic> data = json.decode(response.body);
return data.map((json) => CategoryModel.fromJson(json)).toList();
} else {
throw ServerException(
'Failed to load categories: ${response.reasonPhrase}');
}
}
@override
Future<CategoryDetailModel> getCategoryDetail(
{required String lang,
required String categoryId,
required String page,
required String perPage}) async {
final url = Uri.parse(
'$baseUrl/api/v1/hadeeths/list/?language=$lang&category_id=$categoryId&page=$page&per_page=$perPage');
final response = await client.get(url);
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
CategoryDetailModel categoryDetail = CategoryDetailModel.fromJson(data);
return categoryDetail;
} else {
throw ServerException(
'Failed to load category Hadeeths: ${response.reasonPhrase}');
}
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/models/category_detail_model.dart | import 'package:hadeeth/src/category/data/models/category_hadeeth_model.dart';
import 'package:hadeeth/src/category/data/models/category_meta_model.dart';
import 'package:hadeeth/src/category/domain/entities/category_detail.dart';
class CategoryDetailModel extends CategoryDetail {
CategoryDetailModel({required super.data, required super.meta});
factory CategoryDetailModel.fromJson(Map<String, dynamic> json) {
var dataList = json['data'] as List;
List<CategoryHadeethModel> categoryHadeethList =
dataList.map((e) => CategoryHadeethModel.fromJson(e)).toList();
return CategoryDetailModel(
data: categoryHadeethList,
meta: CategoryMetaModel.fromJson(json['meta']),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/models/category_model.dart | import 'package:hadeeth/src/category/domain/entities/category.dart';
class CategoryModel extends Category {
CategoryModel(
{required super.id,
required super.title,
required super.hadeethsCount,
super.parentId});
factory CategoryModel.fromJson(Map<String, dynamic> json) {
return CategoryModel(
id: json['id'],
title: json['title'],
hadeethsCount: json['hadeeths_count'],
parentId: json['parent_id'],
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/models/category_hadeeth_model.dart | import 'package:hadeeth/src/category/domain/entities/category_hadeeth.dart';
class CategoryHadeethModel extends CategoryHadeeth {
CategoryHadeethModel(
{required super.id, required super.title, required super.translations});
factory CategoryHadeethModel.fromJson(Map<String, dynamic> json) {
return CategoryHadeethModel(
id: json['id'],
title: json['title'],
translations: (json['translations'] as List)
.map((item) => item.toString())
.toList(),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/data | mirrored_repositories/hadeeth/lib/src/category/data/models/category_meta_model.dart | import 'package:hadeeth/src/category/domain/entities/category_meta.dart';
class CategoryMetaModel extends CategoryMeta {
CategoryMetaModel(
{required super.currentPage,
required super.lastPage,
required super.totalItems,
required super.perPage});
factory CategoryMetaModel.fromJson(Map<String, dynamic> json) {
return CategoryMetaModel(
currentPage: json['current_page'],
lastPage: json['last_page'],
totalItems: json['total_items'],
perPage: json['per_page'],
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/categories/categories_banner.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class CategoriesBanner extends StatelessWidget {
const CategoriesBanner({
super.key,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 250,
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'موسوعة',
style: GoogleFonts.almarai().copyWith(fontSize: 18),
),
const SizedBox(
height: 5,
),
Text(
'الأحاديث النبوية',
style: GoogleFonts.almarai().copyWith(fontSize: 35),
),
]),
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/categories/categories_list.dart | import 'package:flutter/material.dart';
import 'package:hadeeth/src/category/domain/entities/category.dart';
import 'package:hadeeth/src/category/presentation/widgets/categories/single_category.dart';
class CategoriesList extends StatelessWidget {
const CategoriesList({super.key, required this.categories});
final List<Category> categories;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondaryContainer,
borderRadius: const BorderRadius.vertical(top: Radius.circular(40))),
child: ListView.builder(
itemCount: categories.length,
itemBuilder: (context, index) {
final category = categories[index];
return SingleCategory(category: category);
},
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/categories/single_category.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hadeeth/src/category/domain/entities/category.dart';
import 'package:hadeeth/src/category/presentation/blocs/category_detail/category_detail_bloc.dart';
import 'package:hadeeth/src/category/presentation/screens/category_detail_screen.dart';
class SingleCategory extends StatelessWidget {
const SingleCategory({
super.key,
required this.category,
});
final Category category;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
context.read<CategoryDetailBloc>().add(GetCategoryDetail(
lang: 'ar', categoryId: category.id, page: '1', perPage: '80'));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CategoryDetailScreen(
categoryId: category.id,
categoryTitle: category.title,
)));
},
child: Container(
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.background,
borderRadius: BorderRadius.circular(10)),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Theme.of(context).colorScheme.secondaryContainer,
width: 1),
),
child: const Icon(
Icons.arrow_back_ios_new_outlined,
size: 14,
)),
Expanded(
child: Text(
category.title,
textAlign: TextAlign.end,
style: GoogleFonts.changa(),
),
),
],
),
// Add more category information as needed
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/category_detail/category_detail_banner.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class CategoryDetailBanner extends StatelessWidget {
const CategoryDetailBanner({super.key, required this.categoryTitle});
final String categoryTitle;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 250,
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'الأحاديث النبوية',
style: GoogleFonts.almarai().copyWith(fontSize: 18),
),
const SizedBox(
height: 5,
),
Text(
categoryTitle,
style: GoogleFonts.almarai()
.copyWith(fontSize: 35, overflow: TextOverflow.ellipsis),
),
]),
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/category_detail/category_detail_item.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hadeeth/src/category/domain/entities/category_hadeeth.dart';
class CategoryDetailItem extends StatelessWidget {
const CategoryDetailItem({
super.key,
required this.categoryHadeeth,
});
final CategoryHadeeth categoryHadeeth;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// context.read<CategoryDetailBloc>().add(GetCategoryDetail(
// lang: 'ar', categoryId: category.id, page: '1', perPage: '40'));
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
// CategoryDetailScreen(categoryId: category.id)));
},
child: Container(
padding: const EdgeInsets.all(20),
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.background,
borderRadius: BorderRadius.circular(10)),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Theme.of(context).colorScheme.secondaryContainer,
width: 1),
),
child: const Icon(
Icons.arrow_back_ios_new_outlined,
size: 14,
)),
const SizedBox(
width: 10,
),
Expanded(
child: Text(
categoryHadeeth.title,
textAlign: TextAlign.end,
style: GoogleFonts.changa().copyWith(),
),
),
],
),
// Add more category information as needed
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/widgets | mirrored_repositories/hadeeth/lib/src/category/presentation/widgets/category_detail/category_detail_list.dart | import 'package:flutter/material.dart';
import 'package:hadeeth/src/category/domain/entities/category_detail.dart';
import 'package:hadeeth/src/category/presentation/widgets/category_detail/category_detail_item.dart';
class CategoryDetailList extends StatelessWidget {
const CategoryDetailList({super.key, required this.categoriesDetail});
final CategoryDetail categoriesDetail;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondaryContainer,
borderRadius: const BorderRadius.vertical(top: Radius.circular(40))),
child: ListView.builder(
itemCount: categoriesDetail.data.length,
itemBuilder: (context, index) {
final categoryHadeeth = categoriesDetail.data[index];
return CategoryDetailItem(categoryHadeeth: categoryHadeeth);
},
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category/category_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:hadeeth/core/error/failures.dart';
import 'package:hadeeth/src/category/domain/entities/category.dart';
import 'package:hadeeth/src/category/domain/usecases/all_categories_usecase.dart';
import 'package:meta/meta.dart';
part 'category_event.dart';
part 'category_state.dart';
class CategoryBloc extends Bloc<CategoryEvent, CategoryState> {
final AllCategoriesUsecase allCategoriesUsecase;
CategoryBloc({required this.allCategoriesUsecase})
: super(CategoryInitial()) {
on<GetAllCategories>(_getAllCategories);
}
void _getAllCategories(
GetAllCategories event, Emitter<CategoryState> emit) async {
emit(CategoryLoading());
final failureOrCategories =
await allCategoriesUsecase.getAllCategories(lang: event.lang);
failureOrCategories.fold((failure) => emit(_mapFailureToState(failure)),
(categories) => emit(CategoryLoaded(categories: categories)));
}
CategoryState _mapFailureToState(Failure failure) {
switch (failure.runtimeType) {
case EmptyDataFailure:
return CategoryEmptyData();
case ServerFailure:
return CategoryError(message: 'Server error: ${failure.message}');
case OfflineFailure:
return CategoryOffline();
default:
return CategoryError(
message: 'Unexpected error: ${failure.toString()}');
}
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category/category_event.dart | part of 'category_bloc.dart';
abstract class CategoryEvent {}
class GetAllCategories extends CategoryEvent {
final String lang;
GetAllCategories({required this.lang});
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category/category_state.dart | part of 'category_bloc.dart';
@immutable
abstract class CategoryState extends Equatable {
@override
List<Object?> get props => [];
}
class CategoryInitial extends CategoryState {}
class CategoryLoading extends CategoryState {}
class CategoryError extends CategoryState {
final String message;
CategoryError({required this.message});
@override
List<Object?> get props => [message];
}
class CategoryOffline extends CategoryState {}
class CategoryEmptyData extends CategoryState {}
class CategoryLoaded extends CategoryState {
final List<Category> categories;
CategoryLoaded({required this.categories});
@override
List<Object?> get props => [categories];
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category_detail/category_detail_event.dart | part of 'category_detail_bloc.dart';
abstract class CategoryDetailEvent extends Equatable {
const CategoryDetailEvent();
@override
List<Object> get props => [];
}
class GetCategoryDetail extends CategoryDetailEvent {
final String lang;
final String categoryId;
final String page;
final String perPage;
const GetCategoryDetail(
{required this.lang,
required this.categoryId,
required this.page,
required this.perPage});
@override
List<Object> get props => [lang, categoryId, page, perPage];
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category_detail/category_detail_state.dart | part of 'category_detail_bloc.dart';
abstract class CategoryDetailState extends Equatable {
const CategoryDetailState();
@override
List<Object> get props => [];
}
final class CategoryDetailInitial extends CategoryDetailState {}
class CategoryDetailLoading extends CategoryDetailState {}
class CategoryDetailError extends CategoryDetailState {
final String message;
const CategoryDetailError({required this.message});
@override
List<Object> get props => [message];
}
class CategoryDetailOffline extends CategoryDetailState {}
class CategoryDetailEmptyData extends CategoryDetailState {}
class CategoryDetailLoaded extends CategoryDetailState {
final CategoryDetail categoriesDetail;
const CategoryDetailLoaded({required this.categoriesDetail});
@override
List<Object> get props => [categoriesDetail];
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation/blocs | mirrored_repositories/hadeeth/lib/src/category/presentation/blocs/category_detail/category_detail_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:hadeeth/core/error/failures.dart';
import 'package:hadeeth/src/category/domain/entities/category_detail.dart';
import 'package:hadeeth/src/category/domain/usecases/category_detail_usecase.dart';
part 'category_detail_event.dart';
part 'category_detail_state.dart';
class CategoryDetailBloc
extends Bloc<CategoryDetailEvent, CategoryDetailState> {
final CategoryDetailUsecase categoryDetailUsecase;
CategoryDetailBloc({required this.categoryDetailUsecase})
: super(CategoryDetailInitial()) {
on<GetCategoryDetail>(_getCategoryDetail);
}
void _getCategoryDetail(
GetCategoryDetail event, Emitter<CategoryDetailState> emit) async {
emit(CategoryDetailLoading());
final failureOrCategories = await categoryDetailUsecase.getCategoryDetail(
categoryId: event.categoryId,
lang: event.lang,
page: event.page,
perPage: event.perPage);
failureOrCategories.fold(
(failure) => emit(_mapFailureToState(failure)),
(categoriesDetail) =>
emit(CategoryDetailLoaded(categoriesDetail: categoriesDetail)));
}
CategoryDetailState _mapFailureToState(Failure failure) {
switch (failure.runtimeType) {
case EmptyDataFailure:
return CategoryDetailEmptyData();
case ServerFailure:
return CategoryDetailError(message: 'Server error: ${failure.message}');
case OfflineFailure:
return CategoryDetailOffline();
default:
return CategoryDetailError(
message: 'Unexpected error: ${failure.toString()}');
}
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation | mirrored_repositories/hadeeth/lib/src/category/presentation/screens/category_detail_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hadeeth/src/category/presentation/blocs/category_detail/category_detail_bloc.dart';
import 'package:hadeeth/src/category/presentation/widgets/category_detail/category_detail_banner.dart';
import 'package:hadeeth/src/category/presentation/widgets/category_detail/category_detail_list.dart';
class CategoryDetailScreen extends StatelessWidget {
const CategoryDetailScreen(
{super.key, required this.categoryId, required this.categoryTitle});
final String categoryId;
final String categoryTitle;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.background,
body: BlocBuilder<CategoryDetailBloc, CategoryDetailState>(
builder: (context, state) {
if (state is CategoryDetailLoading) {
return const SizedBox(
child: Center(child: CircularProgressIndicator()));
} else if (state is CategoryDetailLoaded) {
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
CategoryDetailBanner(
categoryTitle: categoryTitle,
),
Expanded(
child: CategoryDetailList(
categoriesDetail: state.categoriesDetail),
)
],
);
} else if (state is CategoryDetailEmptyData) {
return const Center(
child: Text('No categories available.'),
);
} else if (state is CategoryDetailError) {
return Center(
child: Text('Error: ${state.message}'),
);
} else {
return const Center(
child: Text('Unexpected state'),
);
}
},
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/presentation | mirrored_repositories/hadeeth/lib/src/category/presentation/screens/categories_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hadeeth/src/category/presentation/blocs/category/category_bloc.dart';
import 'package:hadeeth/src/category/presentation/widgets/categories/categories_banner.dart';
import 'package:hadeeth/src/category/presentation/widgets/categories/categories_list.dart';
class CategoriesScreen extends StatelessWidget {
const CategoriesScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.background,
body: BlocBuilder<CategoryBloc, CategoryState>(
builder: (context, state) {
if (state is CategoryLoading) {
return const SizedBox(
child: Center(child: CircularProgressIndicator()));
} else if (state is CategoryLoaded) {
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const CategoriesBanner(),
Expanded(
child: CategoriesList(
categories: state.categories,
),
)
],
);
} else if (state is CategoryEmptyData) {
return const Center(
child: Text('No categories available.'),
);
} else if (state is CategoryError) {
return Center(
child: Text('Error: ${state.message}'),
);
} else {
return const Center(
child: Text('Unexpected state'),
);
}
},
),
);
}
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/domain | mirrored_repositories/hadeeth/lib/src/category/domain/repository/category_repository.dart | import 'package:dartz/dartz.dart';
import 'package:hadeeth/core/error/failures.dart';
import 'package:hadeeth/src/category/domain/entities/category.dart';
import 'package:hadeeth/src/category/domain/entities/category_detail.dart';
abstract class CategoryRepository {
Future<Either<Failure, List<Category>>> getAllCategories(
{required String lang});
Future<Either<Failure, CategoryDetail>> getCategoryDetail(
{required String lang,
required String categoryId,
required String page,
required String perPage});
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/domain | mirrored_repositories/hadeeth/lib/src/category/domain/entities/category_detail.dart | import 'package:hadeeth/src/category/domain/entities/category_hadeeth.dart';
import 'package:hadeeth/src/category/domain/entities/category_meta.dart';
class CategoryDetail {
List<CategoryHadeeth> data;
CategoryMeta meta;
CategoryDetail({required this.data, required this.meta});
}
| 0 |
mirrored_repositories/hadeeth/lib/src/category/domain | mirrored_repositories/hadeeth/lib/src/category/domain/entities/category.dart | class Category {
String id;
String title;
String hadeethsCount;
String? parentId;
Category({
required this.id,
required this.title,
required this.hadeethsCount,
this.parentId,
});
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.