How to save login Credential with Firebase - firebase

I'm having an interface where we should log in by providing the email and password.
Below is my login page.
the interface is designed using dart with flutter.
What I want is to save the email and password when the user (checks the remember me box and then)login to the account.
When the user comes back again to the same page, the page should automatically fill the username and password for the user.
For now, it saves the credentials in the firebase authentication.
Below is my code for Remember me checkbox and login.
Widget _RememberMeCheckbox() {
return Container(
height: 20.0,
child: Row(
children: <Widget>[
Theme(
data: ThemeData(unselectedWidgetColor: Colors.white),
child: Checkbox(
value: _rememberMe,
checkColor: Colors.green,
activeColor: Colors.white,
onChanged: (value) {
setState(() {
_rememberMe = value;
});
},
),
),
Text(
'Remember me',
style: kLabelStyle,
),
],
),
);
}
Widget _LoginBtn() {
return Container(
padding: EdgeInsets.symmetric(vertical: 25.0),
width: double.infinity,
child: Form(
child: RaisedButton(
elevation: 5.0,
onPressed: () async {
final form = formKey.currentState;
form.save();
if (form.validate()) {
try {
FirebaseUser result =
await Provider.of<AuthService>(context, listen: false)
.loginUser(email: _email, password: _password);
print(result);
Navigator.of(context).pushNamed('/home');
} on AuthException catch (ex) {
return _showErrorDialog(context, ex.message);
} on Exception catch (ex) {
return _showErrorDialog(context, ex.toString());
}
}
},
padding: EdgeInsets.all(15.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Colors.white,
child: Text(
'LOGIN',
style: TextStyle(
color: Color(0xFF527DAA),
letterSpacing: 1.5,
fontSize: 18.0,
fontWeight: FontWeight.bold,
fontFamily: 'OpenSans',
),
),
),
),
);
}
I need to do this using firebase can anyone help me?
String_email="";
String_password="";
Widget _EmailTextField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Email',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
keyboardType: TextInputType.text,
autovalidate: false,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.email,
color: Colors.white,
),
hintText: 'Enter your Email Address',
hintStyle: kHintTextStyle,
),
validator: (String value) {
if (value.isEmpty) {
return 'Email is Required.';
}
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if (!regex.hasMatch(value)) {
return 'Enter valid Email Address';
}
return null;
},
onSaved: (String value) {
return _email = value;
},
),
),
],
);
}
Widget _PasswordTextField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Password',
style: kLabelStyle,
),
SizedBox(height: 10.0),
Container(
alignment: Alignment.centerLeft,
decoration: kBoxDecorationStyle,
height: 60.0,
child: TextFormField(
autovalidate: false,
style: TextStyle(
color: Colors.white,
fontFamily: 'OpenSans',
),
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.only(top: 14.0),
prefixIcon: Icon(
Icons.lock,
color: Colors.white,
),
suffixIcon: IconButton(
icon: Icon(
_passwordVisible ? Icons.visibility : Icons.visibility_off,
color: Colors.white,
),
onPressed: _passwordVisibility,
),
hintText: 'Enter your Password',
hintStyle: kHintTextStyle,
),
obscureText: !_passwordVisible,
validator: (String value) {
if (value.isEmpty) {
return 'Password is Required.';
}
if (value.length < 6) {
return 'Password too short.';
}
return null;
},
onSaved: (String value) {
return _password = value;
},
),
),
],
);
}

There are a few options:
Read and write files: https://flutter.io/reading-writing-files/
SQLite via a Flutter plugin: https://github.com/tekartik/sqflite
SQLCipher via a Flutter plugin: https://github.com/drydart/flutter_sqlcipher
SharedPreferences via a Flutter plugin: https://github.com/flutter/plugins/tree/master/packages/shared_preferences

Related

flutter: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() Other responses are not helping me out

I tried using an answer to the same question but I am not sure what else I have to do in my case
import 'package:auduo/routes/routes.dart';
import 'package:auduo/opening_Screen.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: AppRoutes.define(),
home: OpeningScreen(),
);
}
}
Let me know if you need to see other .dart files
Below is the Requested Code From The Comments
import 'package:flutter/material.dart';
import 'package:auduo/routes/routes.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
// Bleyl Dev Vid 2 - 7:49
class Register extends StatefulWidget {
#override
_RegisterViewState createState() => _RegisterViewState();
}
class _RegisterViewState extends State<Register> {
final _formKey = GlobalKey<FormState>();
TextEditingController _usernameController = TextEditingController();
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
TextEditingController _repasswordController = TextEditingController();
#override
Widget build(BuildContext context) {
final mq = MediaQuery.of(context);
final logo = Image.asset(
"assets/Auduo Logo V 1.0.png",
height: mq.size.height / 4,
);
final usernameField = TextFormField(
controller: _usernameController,
style: TextStyle(color: Colors.white),
cursorColor: Colors.white,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.yellow),
),
hintText: "NiceSound259",
labelText: "Username",
labelStyle: TextStyle(color: Colors.white),
hintStyle: TextStyle(
color: Colors.white,
),
),
);
final emailField = TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
style: TextStyle(color: Colors.white),
cursorColor: Colors.white,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.yellow),
),
hintText: "Something#example.com",
labelText: "Email",
labelStyle: TextStyle(color: Colors.white),
hintStyle: TextStyle(
color: Colors.white,
),
),
);
final passwordField = TextFormField(
obscureText: true,
controller: _passwordController,
style: TextStyle(color: Colors.white),
cursorColor: Colors.white,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.yellow),
),
hintText: "password",
labelText: "Password",
labelStyle: TextStyle(color: Colors.white),
hintStyle: TextStyle(
color: Colors.white,
),
),
);
final repasswordField = TextFormField(
obscureText: true,
controller: _repasswordController,
style: TextStyle(color: Colors.white),
cursorColor: Colors.white,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.yellow),
),
hintText: "re-enter password",
labelText: "Re-Enter Password",
labelStyle: TextStyle(color: Colors.white),
hintStyle: TextStyle(
color: Colors.white,
),
),
);
final fields = Padding(
padding: EdgeInsets.only(top: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
usernameField,
emailField,
passwordField,
repasswordField
],
),
);
final registerButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(25),
color: Colors.white,
child: MaterialButton(
minWidth: mq.size.width / 1.2,
padding: EdgeInsets.fromLTRB(10, 15, 10, 15),
child: Text(
"Register",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
onPressed: () async {
try {
User user =
(await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
)) as User;
if (user != null) {
user.updateDisplayName(_usernameController.text);
Navigator.of(context).pushNamed(AppRoutes.home);
}
} catch (e) {
print(e);
_usernameController.text = "";
_passwordController.text = "";
_repasswordController.text = "";
_emailController.text = "";
//TODO alert dialog with error
}
},
),
);
final bottom = Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
//loginButton,
Padding(
padding: EdgeInsets.all(8.0),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Already have an account?",
style: Theme.of(context).textTheme.subtitle1?.copyWith(
color: Colors.white,
),
),
MaterialButton(
onPressed: () {
Navigator.of(context).pushNamed(AppRoutes.authLogin);
},
child: Text(
"Sign In",
style: Theme.of(context).textTheme.subtitle1?.copyWith(
color: Colors.white,
decoration: TextDecoration.underline,
),
),
),
],
),
],
);
return Scaffold(
backgroundColor: Colors.black,
body: Form(
key: _formKey,
child: SingleChildScrollView(
padding: EdgeInsets.all(36),
child: Container(
height: mq.size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
logo,
fields,
registerButton,
Padding(
padding: EdgeInsets.only(bottom: 150),
child: bottom,
)
],
),
),
),
),
);
}
}
Above is the Requested Code From The Comments,
This is the register.dart code the functions are pretty similar to login.dart so hopefully this is enough.
Try running flutter clean and run the app again. another known fix would be to add the optional parameters name and options to the
await Firebase.initializeApp(name: ....., options: .....)
You could also try to minimally reproduce the error by creating the default counter app, add firebase initializations and see if the error persists.

FormatException: Unexpected character (at character 1) error while using email_auth package

#Hello there! I am using email_auth: ^0.0.1+4 Package to confirm the user email also it worked fine for few days and I also registered 2 3 users but suddenly it has started showing this FormatException: Unexpected character (at character 1) and DOCTYPE html error. I have added signup file Please check and help. Thank you.#
SignUp Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vanfly/common.dart';
import 'package:vanfly/providers/user_provider.dart';
import 'package:vanfly/screens/home.dart';
import 'package:vanfly/widgets/loading.dart';
import 'package:email_auth/email_auth.dart';
bool verified = false;
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
TextEditingController otp = TextEditingController();
bool hidePass = true;
void sendOTP() async {
EmailAuth.sessionName = 'Vanfly';
var res = await EmailAuth.sendOtp(receiverMail: _email.value.text);
if (res) {
_key.currentState.showSnackBar(SnackBar(
content: Text("An OTP has sent to your email please verify")));
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
}
}
bool verifyOTP(){
var res = EmailAuth.validate(receiverMail: _email.value.text, userOTP: otp.value.text);
if (res) {
return verified = true;
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
return verified = false;
}
}
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating
? Loading()
: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image(
image: AssetImage(
'images/vanfly Logo/vanfly_logo.png'),
width: 300,
height: 300,
)),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _email,
decoration: InputDecoration(
hintText: "Email",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Verify')),
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(keyboardType: TextInputType.number,
controller: otp,
decoration: InputDecoration(
hintText: "otp",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Resend'),
),
icon: Icon(Icons.pin),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = !hidePass;
});
}),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.pinkAccent,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
verifyOTP();
if (verified == true &&
_formKey.currentState.validate()) {
if (!await user.signUp(_name.text,
_email.text, _password.text)) {
// ignore: deprecated_member_use
_key.currentState.showSnackBar(
SnackBar(
content:
Text("Sign up failed")));
return;
}
changeScreenReplacement(
context, MyHomePage());
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black, fontSize: 16),
))),
],
)),
),
),
],
),
);
}
}
Error
I/flutter ( 5091): Email ID is valid
I/flutter ( 5091): --This error is from the package--
I/flutter ( 5091): FormatException: Unexpected character (at character 1)
I/flutter ( 5091): <!DOCTYPE html>
I/flutter ( 5091): ^
I/flutter ( 5091): --End package error message--
The error is coming from the package itself.
The endpoint that the package calls to send the OTP is down and so it returns an error page instead of the JSON the package expected. This causes an error in parsing the HTML which is why the error says:
FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
I'll advise you to use a different service like firebase_auth for this or create an issue on the project.

flutter and firestore : change price and size dynamicly

hello iam using flutter and firebase in my project , i have a product and evert product have a price , every product have a list of sizes , i want the product to change its price when the size changes .
here is my product document :
i know that i have to change the prices into list but how to link them together in firebase or flutter .
this is my code :
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: CustomText(
text: "Select a Size",
color: Colors.white,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: DropdownButton<String>(
value: _size,
style: TextStyle(color: Colors.white),
items: widget.product.sizes
.map<DropdownMenuItem<String>>(
(value) => DropdownMenuItem(
value: value,
child: CustomText(
text: value,
color: Colors.red,
)))
.toList(),
onChanged: (value) {
setState(() {
_size = value;
});
}),
)
],
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"${widget.product.description}",
style: TextStyle(color: Colors.white)),
),
),
Padding(
padding: const EdgeInsets.all(9),
child: Material(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
appProvider.changeIsLoading();
bool success = await userProvider.addToCart(
product: widget.product,
size: _size);
if (success) {
toast("Added to Cart!");
userProvider.reloadUserModel();
appProvider.changeIsLoading();
return;
} else {
toast("Not added to Cart!");
appProvider.changeIsLoading();
return;
}
},
minWidth: MediaQuery.of(context).size.width,
child: appProvider.isLoading
? Loading()
: Text(
"Add to cart",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
SizedBox(
height: 20,
)
],
),
),
)
],
There is trigger for widget :
onChanged: (value) {
setState(() {
_size = value;
reference.setData({quantity : value}, merge: true)
});
}),
Just change the reference to document path.

How to add "this user/account does not exist" error in Flutter, using Firebase?

I am trying to make a login page in Flutter. I have used Firebase as well for user authentication and logging in. The problem is, while I can login successfully with the correct information, I am unable to display anything like a pop up error box or message that the account does not exist. This is my code :
class _LoginPageState extends State<LoginPage> {
String _email, _password;
final auth = FirebaseAuth.instance;
bool hidepwd = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
brightness: Brightness.light,
backgroundColor: Colors.transparent,
elevation: 0,
leading: Container(
margin: EdgeInsets.all(5),
width: 50,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
color: Color(0xffe9eefa),
),
child: IconButton(
onPressed: (){Navigator.pop(context);},
icon: Icon(
Icons.keyboard_arrow_left_rounded,
color: Color(0xff2657ce),
),
),
),
),
body: ListView(
children: <Widget>[
Container(
child: IconButton(
icon: Icon(
Icons.account_circle_rounded,
color: Color(0xff2657ce),
size:100,
),
),
),
SizedBox(height: 50,),
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.only(right: 240),
child: Text('Email Address', style: TextStyle(
fontSize: 15,),),
),
SizedBox(height: 10,),
Container(
padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.grey.withOpacity(0.2),
),
child: TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: 'Email',
),
onChanged: (value) {
setState(() {
_email = value.trim();
});
},
),
),
SizedBox(height: 20,),
Container(
padding: EdgeInsets.only(right: 270),
child: Text('Password', style: TextStyle(
fontSize: 15,
),),
),
SizedBox(height: 10,),
Container(
padding: EdgeInsets.symmetric(vertical: 2, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.grey.withOpacity(0.2),
),
child: Row(
children: <Widget>[
Expanded(
child: TextFormField(
obscureText: hidepwd,
decoration: InputDecoration(hintText: 'Password'),
onChanged: (value) {
setState(() {
_password = value.trim();
});
},
),
),
Container(
height: 50,
width: 50,
child: IconButton(
onPressed: togglepwdVisibility,
icon: IconButton(
icon: hidepwd == true ? Icon(
Icons.visibility_off
): Icon(Icons.visibility),
),
),
)
],
),
),
SizedBox(height: 20,),
RaisedButton(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
color: Color(0xff5178D7),
child: Text("Log In", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 15
),),
onPressed: (){
auth.signInWithEmailAndPassword(email: _email, password: _password).then((_){
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => frontpage()));
});
}
),
SizedBox(height: 20,),
Container(
child: Center(
child: Text('---- or ----'),
),
),
SizedBox(height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Don't have an account? "),
InkWell(
onTap: openSignUpPage,
child: Text("Sign Up", style: TextStyle(
color: Color(0xff1A3C90),
fontWeight: FontWeight.w700
),),
)
],
)
],
),
),
),
],
),
);
}
Any ideas/suggestions on what I could add or change in my code to have that error message included when I am unable to login overall?
In your login onPressed: (){ ... }, catch the FirebaseAuthException.
Source: https://firebase.flutter.dev/docs/auth/usage/#sign-in
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: "barry.allen#example.com",
password: "SuperSecretPassword!"
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
If you need alerts to pop on each login error you can try using the following function but only if you are using TextEdittingController:
signIn() async {
if (_loginFormKey.currentState!.validate()) {
_loginFormKey.currentState!.save();
try {
await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text)
.then((currentUser) => FirebaseFirestore.instance
.collection("users")
.doc(currentUser.user!.uid)
.get()
.then((conext) => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage())))
.catchError((err) => print(err)));
} on FirebaseAuthException catch (error) {
if (error.code == 'user-not-found') {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Auth Exception!"),
content: Text("This User Does Not Exist."),
actions: <Widget>[
Row(
children: [
ElevatedButton(
child: Text("Sign In Again"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
)
],
);
});
} else if (error.code == 'wrong-password') {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Auth Exception!"),
content: Text("The Password Entered is Invalid."),
actions: <Widget>[
Row(
children: [
ElevatedButton(
child: Text("Sign In Again"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
)
],
);
});
}
}
}
}

Retrieving Data From Firestore in time

I have looked all over the internet for how to fix this problem and I can't find a solution anywhere. I am using flutter with firestore to make an app. I want to make it so when the user logins into the app at the top shows their name (simple right). I can get data from firestore:
Future<void> getName() async {
print("Attemping to get name!");
final firestoreInstance = await FirebaseFirestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
await firestoreInstance.collection("Users").doc(uid).get().then((value) {
print("Name: " + value.data()["firstName"]);
info.firstName=((value.data()["firstName"]));
})
class info {
static String firstName;
}
but it comes in too late so the app just says "Welcome back" As you can see here and not "Welcome back, Connor" As seen here
When I look in the console the function does run but the program doesn't wait for it and continues resulting in a null.
Thanks you
EDIT as requested UI code:
class Home extends StatelessWidget {
final DatabaseReference = FirebaseDatabase.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
static String firstName;
static String lastName;
static String email;
static String companyName;
static bool isNewAccount = false;
static String name = "Welcome back";
Home();
#override
Widget build(BuildContext context) {
final User user = auth.currentUser;
final uid = user.uid;
final ref = DatabaseReference.reference();
if (isNewAccount == true) {
userSetup(firstName, lastName, email, companyName);
isNewAccount = false;
}
getName(); //does get the name from the database but name will error out as it doesn't get the name fast enough (or that's what I think)
name= "Welcome back, "+info.firstName;
return WillPopScope(
onWillPop: () async => false,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.cyan,
body: SingleChildScrollView(
child: Container(
margin:
EdgeInsets.only(top: MediaQuery.of(context).size.height / 16),
child: Column(
children: [
Container(
margin: EdgeInsets.only(bottom: 10),
child: Text(
name,
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: MediaQuery.of(context).size.width / 16,
),
),
),
Container(
width: 260,
height: 125,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-IN",
style: new TextStyle(
color: Colors.white,
fontSize: 40.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Checkin()));
},
),
),
Container(
width: 260,
height: 140,
padding: EdgeInsets.only(top: 20),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-OUT",
style: new TextStyle(
color: Colors.white,
fontSize: 38.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Checkout()));
},
),
),
Container(
margin: EdgeInsets.only(top: 55),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"Sign out: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"SIGN OUT",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
context.read<AuthenticationService>().signOut();
//return MyApp();
},
),
)
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Stats: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"STATS",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));
},
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Profile: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"PROFILE",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));*/
},
),
),
],
),
),
Container(
width: 240,
height: 55,
margin: EdgeInsets.only(
top: MediaQuery.of(context).size.height / 12),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"EMERGENCY REPORT",
style: new TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => EmergencyReport()));
},
),
),
],
),
),
),
),
),
);
}
static getAccountDetails(
String firstName1, String lastName1, String email1, String companyName1) {
firstName = firstName1;
lastName = lastName1;
email = email1;
companyName = companyName1;
isNewAccount = true;
}
static getFirstName(String nameFirst) {
name = "Welcome back, "+nameFirst;
}
}
FutureBuilder<DocumentSnapshot>(
future: firestoreInstance.collection("Users").doc(uid).get(),
builder: (_,snap){
return snap.hasData ? Text(snap.data.data()["firstName"]):CircularProgressIndicator();
},)
You need to convert StatelessWidget into StatefullWidget.
After that you have to write this in initState method
void initState() {
super.initState();
getName().then((){
setState(() {
name= "Welcome back, "+info.firstName;
});
});
}

Resources