How do I add snackbar? - firebase

I dont know why the Snackbar doesnt show up.But when I delete the function off the firebaseauth it shows the snackbar.
Code:
MaterialButton(
onPressed: (){
try{
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text).then((signedUser) {
userCollection.doc(signedUser.user?.uid).set({
'username': usernameController.text,
'email': emailController.text,
'password': passwordController.text,
'uid': signedUser.user?.uid,
});
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeScreen()));
});
} catch(e) {
print(e.toString());
var snackbar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackbar);
}
},
elevation: 0,
minWidth: MediaQuery.of(context).size.width,
height: 40.h,
child: Text("Buat akun"),
textColor: Colors.white,
color: Colors.blue,
)

you are using then so the error won't be caught in the catch section.
You should remove the try catch block and catch the error with catchError() instead like this:
FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text).then((signedUser) {
userCollection.doc(signedUser.user?.uid).set({
'username': usernameController.text,
'email': emailController.text,
'password': passwordController.text,
'uid': signedUser.user?.uid,
});
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => HomeScreen()));
}).catchError((e) {
print(e.toString());
var snackbar = SnackBar(content: Text(e.toString()));
ScaffoldMessenger.of(context).showSnackBar(snackbar);
});

Related

How to fetch current user(Logged In user) details from particular collection in firebase?

Registration.dart
In this code we have tried to register a user i.e. doctor details in the collection named 'doctor' and after registering it is navigating to login page(Login_Screen.dart). We are able to fetch and display current user name and email id ({user?.displayName},{user?.email}),but we are struggling to fetch other details of that user from collection 'doctor'.
child: RaisedButton(
textColor: Color(0xFF003058),
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
color: Colors.orange[700],
child: Text('Register',
style: TextStyle(
fontSize: 22.0, fontWeight: FontWeight.w900)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
onPressed: () async {
if (!_formKey.currentState!.validate()) {
return;
} else {
await Doctors.add({
"name": _name,
"email": _email,
"license": _license,
"password": _password,
"cpassword": _cpassword,
"role":role
}).then((value) => print("Doctors details Added"));
try {
UserCredential user =
await auth.createUserWithEmailAndPassword(
email: _email, password: _password);
if (user != null) {
await auth.currentUser!
.updateProfile(displayName: _name);
}
} catch (e) {
print(e);
}
}
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
_formKey.currentState!.save();
},
),
Login_Screen.dart
child: RaisedButton(
textColor: Color(0xFF003058),
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
color: Colors.orange[700],
child: Text('Sign in',
style: TextStyle(
fontSize: 22.0, fontWeight: FontWeight.w900)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
onPressed: () async {
if (!_formKey.currentState!.validate()) {
return;
} else {
try {
final user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
))
.user;
if (user != null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => App()),
);
}
} catch (e) {
print(e);
}
}
_formKey.currentState!.save();
print(emailController.text);
print( passwordController.text);
},
),
This would depend on how you are storing the current user data in the collection,
if you are storing the current users data in a collection with location "Users/userID" where userID is the user's id , you can reach the user's data like:
await users.doc("Users/${FirebaseAuth.instance.currentUser!.uid}").get();
and in case you mean reaching the current logged in data in general, not the data that you store in a collection, you can do so simpley by calling:
FirebaseAuth.instance.currentUser!.uid : to get the current user id (as we did above)
FirebaseAuth.instance.currentUser!.phoneNumber: to get the current user's phone number.
FirebaseAuth.instance.currentUser!.displayName: to get the current user's display name.
and there are other kinds of data you can get.

flutter phone auth doens't work in my boss phone

helllo
I'm trying to make phone auth with flutter
I managed to implement but doens't work in my boss phone (android)
in my phone it works.
that's why I'm almost crazy
I wanna connect boss phone with cable debug mode
but my boss refused to it. 😫😫😫
here's my code
Future createUserWithPhone({String phoneNumber, BuildContext context}) async {
String phoneNumberWith82 = '+82 $phoneNumber';
await fAuth.verifyPhoneNumber(
phoneNumber: phoneNumberWith82,
timeout: Duration(seconds: 60),
verificationCompleted: (AuthCredential authCredential) async {
print('here verificationcompleted');
✅ not a big deal, verificationCompleted doesn't work don't know why
await fAuth
.signInWithCredential(authCredential)
.then((AuthResult result) {
Fluttertoast.showToast(
msg: "success",
backgroundColor: Colors.black26,
textColor: Colors.white,
);
}).catchError((e) {
print('Error Occurs ⭐3');
return "error";
});
},
verificationFailed: (AuthException exception) {
Fluttertoast.showToast(
msg: 'too many request',
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
return "error";
},
codeSent: (String verificationId, [int forceResendingToken]) async {
final _codeController = TextEditingController();
await showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: Text("write auth 6digit"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: _codeController,
keyboardType: TextInputType.number,
),
],
),
actions: <Widget>[
FlatButton(
child: Text("verify"),
textColor: Constants.kPrimaryOrange,
// color: Constants.kPrimaryOrange,
onPressed: () async {
var _credential = PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: _codeController.text.trim());
✅ Error Occurs HERE ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
await fAuth
.signInWithCredential(_credential)
.then((AuthResult result) async {
var snapshot = await Firestore.instance
.collection('users')
.where('pid', isEqualTo: result.user.phoneNumber)
.getDocuments();
/// id doesn't exist.
if (snapshot.documents.length == 0) {
await Firestore.instance
.collection('users')
.document(result.user.uid)
.setData({
'uid': result.user.uid,
'pid': result.user.phoneNumber,
'name': randomName,
'createdAt': DateTime.now(),
'storeName': '',
});
Fluttertoast.showToast(
msg: "33",
backgroundColor: Colors.black26,
textColor: Colors.white,
);
} else {
Fluttertoast.showToast(
msg: " id exists",
backgroundColor: Colors.black26,
textColor: Colors.white,
);
}
setUser(result.user);
Navigator.pushNamedAndRemoveUntil(
context, SplashScreen.id, (route) => false,
arguments: result.user);
✅ catch }).catchError((e) {
Fluttertoast.showToast(
msg: e.toString(),
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ErrorReading(errorMsg: e.toString())),
);
// Navigator.pop(context);
return "error";
});
},
),
FlatButton(
child: Text("close"),
textColor: Constants.kPrimaryOrange,
// color: Constants.kPrimaryOrange,
onPressed: () {
print('Error Occurs ⭐');
Navigator.pop(context);
},
)
],
),
);
},
codeAutoRetrievalTimeout: (String verificationId) {
verificationId = verificationId;
});
I don't know cause of this problem , so i cannot fix it.
I used to toast to find error point.
then i found it ✅ look at this emoji
anybody?
firebase_auth: ^0.16.1
firebase_core: ^0.4.0
cloud_firestore: ^0.13.0
firebase_storage: ^3.1.6
I tryed firebase_auth ^18 with core ^5 but many place to change recent code so I trying to figuring out with these versions
Follow the steps as mentioned here.
You need to add both the SHA-1 Fingerprint and enable the Device Check API for Phone Auth to work in Android.
If you need a code sample for Phone Auth to work in
firebase_auth ^18 with core ^5, do let me know will edit this answer.

Flutter/Firebase/Firestore - Signup not pushing data to database

I am trying to record some additional user data when they sign up to my app. My signup process looks like this:
String ref = "users";
Future<bool> signUp(
String email,
String password,
String firstName,
String lastName,
) async {
try {
_status = Status.Authenticating;
notifyListeners();
await _auth
.createUserWithEmailAndPassword(email: email, password: password);
FirebaseFirestore.instance.collection(ref).doc(user.uid).set({
'id': user.uid,
'displayName': firstName.trim() + " " + lastName.trim(),
'email': email.trim(),
'createdat': DateTime.now()
});
return true;
} catch (e) {
_status = Status.Unauthenticated;
notifyListeners();
} return false;
}
I can't work out why, when the user enters their data and signs up, the specified values aren't pushed to firestore. Can someone help me out? Thanks. Here is where I have implemented my code:
child: RaisedButton(
child: Text('Create an Account', style: TextStyle(color: Colors.white),),
onPressed: () async {
if (validate()) {
_formKey.currentState.reset();
user.signUp(_emailController.text, _passwordController.text, _firstNameController.text, _lastNameController.text);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => Home()));
}
}),
So, as mentioned in the comments, it should be like this:
await FirebaseFirestore.instance.collection(ref).doc(user.uid).set({
'id': user.uid,
'displayName': firstName.trim() + " " + lastName.trim(),
'email': email.trim(),
'createdat': DateTime.now()
});

FirabaseAuth can't catch exception in Flutter

I'm working on a signup screen for my app. I implemented firebase and can authenticate user and save some user info into firebase database succesfully. I started to check if userName field is empty or not. But firebase sometimes can not catch exception about bad formatted email address. It works for password (min 6 char) everytime but sometimes work for email. I can't find any solution. Here is my code. Is there anybody who have an idea?
onPressed: () async {
if (validateName(userName) && validateEmail(email)) {
setState(() {
showSpinner = true;
});
try {
final newUser =
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
//get name and update user profile
UserUpdateInfo userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = userName;
FirebaseUser user = await _auth.currentUser();
await user.updateProfile(userUpdateInfo);
await user.reload();
Navigator.pushNamed(context, NavigationScreen.id);
}
setState(() {
showSpinner = false;
});
} on PlatformException catch (e) {
setState(() {
showSpinner = false;
});
Fluttertoast.showToast(
msg: e.message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor: Colors.white,
textColor: Colors.red,
fontSize: 18.0,
);
}
} else {
Fluttertoast.showToast(
msg: 'You must ente all information',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor: Colors.white,
textColor: Colors.red,
fontSize: 18.0,
);
}
},
//name TextField validation
bool validateName(String name) {
if (name != null && name.length > 2) {
return true;
} else {
return false;
}
}
//email TextField validation
bool validateEmail(String email) {
if (email != null) {
return true;
} else {
return false;
}
}
createUserWithEmailAndPassword returns a Future<AuthResult>, to catch the error you can do the following:
final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password).catchError((err) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
FlatButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
Using catchError, it will handles errors emitted by this Future, and then showDialog will display a dialog with the error.

How to make register using email/password and send Code to the phone in Firebase

I want to allow users to register an account on my app using flutter with email/password, and then send code to the phone. So when user enters their data to Sign up, it should register them with their email and then use their phone to the verity code. Also the user can't complete the registration and go to the Home page Without checking the entered code.
But in my code it's not working what i want do it.
My click function:
dynamic ruselt= await _auth.regsiterwithemail(_emailcontroller.text,_passwordcontroller.text);
if (ruselt!=null){
setState(() async {
loading =false;
verfitycode().verfityphoen(context);
});
}else{
setState(() {
loading=false;
SweetAlert.show(context,
title: "Title",
style: SweetAlertStyle.confirm,
subtitle: "Subtitle");
});
}
My registration function:
Future regsiterwithemail(String email , String password )
async {
try{
AuthResult result =await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user =result.user;
print('oky');
return _userfirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
class for verity code
class verfitycode {
String phonenumber;
String smsCode;
String vialdid;
GlobalKey<FormState>_form;
Future<void> verfityphoen(BuildContext context)async{
final PhoneCodeAutoRetrievalTimeout AutoRetriv =(String verid) {
this.vialdid =verid;
};
final PhoneCodeSent smsCodeset =(String verid,[int forceResendingToken]){
this.vialdid=verid;
smscodeDialog(context);
};
final PhoneVerificationCompleted verfiedcompletd=(AuthCredential user){
print('verfild');
};
final PhoneVerificationFailed verfilederror =(AuthException exception){
print('${exception.message}');
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber:"+967776523152",
timeout: const Duration(seconds:5),
verificationCompleted: verfiedcompletd,
verificationFailed: verfilederror,
codeSent: smsCodeset,
codeAutoRetrievalTimeout: AutoRetriv
);
}
Future<bool> smscodeDialog(BuildContext context){
Alert(
context: context,
title: "رمز التحقق",
content: Column(
children: <Widget>[
Form(
key: _form,
child: Directionality(
textDirection: TextDirection.rtl,
child:
TextField(
onChanged: (val){
this.smsCode=val;
},
decoration:InputDecoration (
icon: Icon(Icons.supervisor_account),
labelText: 'ادخل رمز التحقق',
),
),
)
)
],
),
buttons: [
DialogButton(
child: Text('خروج', style: TextStyle(color: Colors.white, fontSize:18)), onPressed:()=>Navigator.pop(context)),
DialogButton(
onPressed: (){
// _form.currentState.validate();
FirebaseAuth.instance.currentUser().then((user) {
if (user != null) {
Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => Home()));
} else {
Navigator.pop(context);
_testSignlink();
}
});
},
child: Text(
"ادخل الرمز",
style: TextStyle(color: Colors.white, fontSize:18),
),
),
]).show();
}
_testSignlink() async {
FirebaseUser user;
String _smsCodeController;
final AuthCredential credential = PhoneAuthProvider.getCredential(
verificationId: vialdid,
smsCode: smsCode,
);
await user.linkWithCredential(credential).then((user){
print(user.user.uid);
}).catchError((onError){
print(onError.toString());
});
_smsCodeController = '';
return 'signInWithPhoneNumber succeeded: $user';
}
}

Resources