0% found this document useful (0 votes)
8 views16 pages

Lab 9

App development
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

Lab 9

App development
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

9: Create forgot password option for Pizza Store App using Existing email to get

password reset link.


main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:lab9/login.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
// Check for Errors
if (snapshot.hasError) {
print("Something Went Wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
return MaterialApp(
title: 'Flutter Firebase EMail Password Auth',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
debugShowCheckedModeBanner: false,
home: Login(),
);
});
}
}

signup.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lab9/login.dart';

class Signup extends StatefulWidget {


Signup({Key? key}) : super(key: key);

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

class _SignupState extends State<Signup> {


final _formKey = GlobalKey<FormState>();

var email = "";


var password = "";
var confirmPassword = "";
// Create a text controller and use it to retrieve the current value
// of the TextField.
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();

@override
void dispose() {
// Clean up the controller when the widget is disposed.
emailController.dispose();
passwordController.dispose();
confirmPasswordController.dispose();
super.dispose();
}

registration() async {
if (password == confirmPassword) {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
print(userCredential);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.redAccent,
content: Text(
"Registered Successfully. Please Login..",
style: TextStyle(fontSize: 20.0),
),
),
);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Login(),
),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print("Password Provided is too Weak");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
"Password Provided is too Weak",
style: TextStyle(fontSize: 18.0, color: Colors.black),
),
),
);
} else if (e.code == 'email-already-in-use') {
print("Account Already exists");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
"Account Already exists",
style: TextStyle(fontSize: 18.0, color: Colors.black),
),
),
);
}
}
} else {
print("Password and Confirm Password doesn't match");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
"Password and Confirm Password doesn't match",
style: TextStyle(fontSize: 16.0, color: Colors.black),
),
),
);
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("User SignUp"),
),
body: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: ListView(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: InputDecoration(
labelText: 'Email: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Email';
} else if (!value.contains('@')) {
return 'Please Enter Valid Email';
}
return null;
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: passwordController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password';
}
return null;
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'Confirm Password: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: confirmPasswordController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password';
}
return null;
},
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState!.validate()) {
setState(() {
email = emailController.text;
password = passwordController.text;
confirmPassword = confirmPasswordController.text;
});
registration();
}
},
child: Text(
'Sign Up',
style: TextStyle(fontSize: 18.0),
),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Already have an Account? "),
TextButton(
onPressed: () => {
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder:
(context, animation1, animation2) =>
Login(),
transitionDuration: Duration(seconds: 0),
),
)
},
child: Text('Login'))
],
),
)
],
),
),
),
);
}
}

login.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lab9/dashboard.dart';
import 'package:lab9/forgotpassword.dart';
import 'package:lab9/signup.dart';

class Login extends StatefulWidget {


Login({Key? key}) : super(key: key);

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

class _LoginState extends State<Login> {


final _formKey = GlobalKey<FormState>();

var email = "";


var password = "";
// Create a text controller and use it to retrieve the current value
// of the TextField.
final emailController = TextEditingController();
final passwordController = TextEditingController();

userLogin() async {
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Dashboard(),
),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print("No User Found for that Email");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
"No User Found for that Email",
style: TextStyle(fontSize: 18.0, color: Colors.black),
),
),
);
} else if (e.code == 'wrong-password') {
print("Wrong Password Provided by User");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
"Wrong Password Provided by User",
style: TextStyle(fontSize: 18.0, color: Colors.black),
),
),
);
}
}
}

@override
void dispose() {
// Clean up the controller when the widget is disposed.
emailController.dispose();
passwordController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("User Login"),
),
body: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: ListView(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: InputDecoration(
labelText: 'Email: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Email';
} else if (!value.contains('@')) {
return 'Please Enter Valid Email';
}
return null;
},
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: passwordController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password';
}
return null;
},
),
),
Container(
margin: EdgeInsets.only(left: 60.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState!.validate()) {
setState(() {
email = emailController.text;
password = passwordController.text;
});
userLogin();
}
},
child: Text(
'Login',
style: TextStyle(fontSize: 18.0),
),
),
TextButton(
onPressed: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgotPassword(),
),
)
},
child: Text(
'Forgot Password ?',
style: TextStyle(fontSize: 14.0),
),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Don't have an Account? "),
TextButton(
onPressed: () => {
Navigator.pushAndRemoveUntil(
context,
PageRouteBuilder(
pageBuilder: (context, a, b) => Signup(),
transitionDuration: Duration(seconds: 0),
),
(route) => false)
},
child: Text('Signup'),
),
TextButton(
onPressed: () => {
Navigator.pushAndRemoveUntil(
context,
PageRouteBuilder(
pageBuilder: (context, a, b) => Dashboard(),
transitionDuration: Duration(seconds: 0),
),
(route) => false)
},
child: Text('Dashboard'),
),
],
),
)
],
),
),
),
);
}
}

forgotpassword.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lab9/login.dart';
import 'package:lab9/signup.dart';

class ForgotPassword extends StatefulWidget {


ForgotPassword({Key? key}) : super(key: key);

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

class _ForgotPasswordState extends State<ForgotPassword> {


final _formKey = GlobalKey<FormState>();
var email = "";

// Create a text controller and use it to retrieve the current value


// of the TextField.
final emailController = TextEditingController();

@override
void dispose() {
// Clean up the controller when the widget is disposed.
emailController.dispose();
super.dispose();
}

resetPassword() async {
try {
await FirebaseAuth.instance.sendPasswordResetEmail(email: email);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
'Password Reset Email has been sent !',
style: TextStyle(fontSize: 18.0),
),
),
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
'No user found for that email.',
style: TextStyle(fontSize: 18.0),
),
),
);
}
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reset Password"),
),
body: Column(
children: [
Container(
margin: EdgeInsets.only(top: 20.0),
child: Text(
'Reset Link will be sent to your email id !',
style: TextStyle(fontSize: 20.0),
),
),
Expanded(
child: Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: ListView(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
decoration: InputDecoration(
labelText: 'Email: ',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle:
TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: emailController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Email';
} else if (!value.contains('@')) {
return 'Please Enter Valid Email';
}
return null;
},
),
),
Container(
margin: EdgeInsets.only(left: 60.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState!.validate()) {
setState(() {
email = emailController.text;
});
resetPassword();
}
},
child: Text(
'Send Email',
style: TextStyle(fontSize: 18.0),
),
),
TextButton(
onPressed: () => {
Navigator.pushAndRemoveUntil(
context,
PageRouteBuilder(
pageBuilder: (context, a, b) => Login(),
transitionDuration: Duration(seconds: 0),
),
(route) => false)
},
child: Text(
'Login',
style: TextStyle(fontSize: 14.0),
),
),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Don't have an Account? "),
TextButton(
onPressed: () => {
Navigator.pushAndRemoveUntil(
context,
PageRouteBuilder(
pageBuilder: (context, a, b) =>
Signup(),
transitionDuration:
Duration(seconds: 0),
),
(route) => false)
},
child: Text('Signup'))
],
),
)
],
),
),
),
),
],
),
);
}
}

changepassword.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:lab9/login.dart';

class ChangePassword extends StatefulWidget {


ChangePassword({Key? key}) : super(key: key);

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

class _ChangePasswordState extends State<ChangePassword> {


final _formKey = GlobalKey<FormState>();

var newPassword = "";


// Create a text controller and use it to retrieve the current value
// of the TextField.

final newPasswordController = TextEditingController();

@override
void dispose() {
// Clean up the controller when the widget is disposed.
newPasswordController.dispose();
super.dispose();
}

final currentUser = FirebaseAuth.instance.currentUser;


changePassword() async {
try {
await currentUser!.updatePassword(newPassword);
FirebaseAuth.instance.signOut();
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Login()),
);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.orangeAccent,
content: Text(
'Your Password has been Changed. Login again !',
style: TextStyle(fontSize: 18.0),
),
),
);
} catch (e) {}
}

@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: ListView(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: TextFormField(
autofocus: false,
obscureText: true,
decoration: InputDecoration(
labelText: 'New Password: ',
hintText: 'Enter New Password',
labelStyle: TextStyle(fontSize: 20.0),
border: OutlineInputBorder(),
errorStyle: TextStyle(color: Colors.redAccent, fontSize: 15),
),
controller: newPasswordController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password';
}
return null;
},
),
),
ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState!.validate()) {
setState(() {
newPassword = newPasswordController.text;
});
changePassword();
}
},
child: Text(
'Change Password',
style: TextStyle(fontSize: 18.0),
),
),
],
),
),
);
}
}

dashboard.dart
import 'package:flutter/material.dart';

class Dashboard extends StatelessWidget {


const Dashboard({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
// Material App
return MaterialApp(
home:Scaffold(
appBar: AppBar(
title: Text("CMR INSTITUTE OF TECHNOLOGY"),
centerTitle: true,
backgroundColor: Colors.deepOrange,
),
body: Center(
child: Image(
image:
NetworkImage('https://i0.wp.com/cmrithyderabad.edu.in/wp-content/uploads/2021/09/
cropped-CMR-IT-logo-1.webp?w=731&ssl=1'),
),
)
));
}
}

You might also like