Flutter Connection State Management - flutter

Hello I am doing my fist App in Flutter and i am just setting up the authentication with FireBase, and a mistake its happenning. Im trying to manage the state and navigate between Home and Login with the streambuilder, and its working fine but only if i do a hot restart on Android Studio after registering a new user. After the hot reload it works fine, i am able to login with any of the existing users and it navigates to the home screen, and when i log out goes back to login screen, but if i create new user than just stops working, the screens do not alterate anymore when i log in with any of the old users...
here its my main
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primaryColor: cPrimary),
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.active){
if(snapshot.hasData){
return Home_Screen();
} else if (snapshot.hasError){
return Center(child: Text('${snapshot.error}'),);
}
} else if (snapshot.connectionState == ConnectionState.waiting){
return Center(child: CircularProgressIndicator(color: cPrimary,));
}
return LoginScreen();
}
)
);
}
}
Here is my login and register functions
//Sign Up
Future <void> signUp({
required String email,
required String password,
required String username,
}) async {
try {
if(email.isNotEmpty && password.isNotEmpty && username.isNotEmpty){
UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//add user to database
await _firestore.collection('users').doc(userCredential.user!.uid).set({
'username' : username,
'email' : email,
'uid' : userCredential.user!.uid,
});
}
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
//Log In
Future <void> logIn({
required String email,
required String password,
}) async {
try {
if(email.isNotEmpty && password.isNotEmpty ){
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);}
} 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.');
}
}
}
and here its how i am calling the functions on my screens
ElevatedButton(
onPressed: () async {
setState(() {
_isLoading = true;
});
await AuthService().logIn(
email: _emailController.text,
password: _passwordController.text,);
setState(() {
setState(() {
_isLoading = false;
});
});
},
ElevatedButton(
onPressed: () async {
setState(() {
_isLoading = true;
});
await AuthService().signUp(
email: _emailController.text,
password: _passwordController.text,
username: _usernameController.text,
);
setState(() {
_isLoading = false;
});

After creating the user account, ensure you log in as well.
//Sign Up
Future <void> signUp({
required String email,
required String password,
required String username,
}) async {
try {
if(email.isNotEmpty && password.isNotEmpty && username.isNotEmpty){
UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//add user to database
await _firestore.collection('users').doc(userCredential.user!.uid).set({
'username' : username,
'email' : email,
'uid' : userCredential.user!.uid,
});
}
// add this
await logIn(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}

Related

How to get user credential while moving to welcome screen in flutter

I have created simple home screen for login and register,
Here I have taken readymade code from a channel, and now I need to change little bit..
code is simple, so no more details to explain
just I want to pass Usercredential to my welcome screen...
here is my code
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context,snapshot){
if(snapshot.hasData)
{
print(snapshot.data);
return WelcomePage(usercredential:
//how to get usercredential,
);
}
else
{
return AuthPage();
}
},
),
);
}
}
here is my login page's login code
Future signin() async {
UserCredential? usercredential;
try {
usercredential=await FirebaseAuth.instance.signInWithEmailAndPassword(
email: txtemailcontroller.text, password: txtpasswordcontroller.text);
} on FirebaseAuthException catch (e) {
print("Error is =" + e.toString());
}
}
and register page's register code
Future signup() async {
UserCredential? usercredential;
try {
if (txtconfirmpasswordcontroller.text.trim() ==
txtpasswordcontroller.text.trim()) {
usercredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: txtemailcontroller.text,
password: txtpasswordcontroller.text);
} else {
print("passwrod does not match");
}
} on FirebaseAuthException catch (e) {
print('Error while register' + e.toString());
}
if (usercredential != null) {
String userid = usercredential.user!.uid;
UserModel newuser = UserModel(
email: txtemailcontroller.text,
userid: userid,
fullname:
txtfirstnamecontroller.text + ' ' + txtlastnamecontroller.text,
profilepicture: '');
}
}
so far I know, user credential generated while createuserwithemailandpassword and signinwithemailandpassword method, but how to get it here....where I need...
Add this In your Welcome page:
User? currentUser=FirebaseAuth.instance.currentUser;
Then you can call it any where and get user details like email & id & display name.
for example:
currentUser.email
or
currentUser.uid

The name 'FirebaseAuthExceptions' isn't a type and can't be used in an on-catch clause

I Got This Weird Error:
"The name 'FirebaseAuthExceptions' isn't a type and can't be used in an on-catch clause."
TextButton(
onPressed: () async {
final email = _email.text;
final password = _password.text;
try { final userCredential =
await FirebaseAuth.instance.signInWithEmailAndPassword (
email: email,
password: password,
);
print(userCredential);
} on FirebaseAuthExceptions catch (e){
If (e.code == 'user-not-found') {
print("User is not Found");
} Else if (e.code == 'wrong password') {
print("Wrong Password");
}
}
},
child: Text("LogIn"),
),
It will be FirebaseAuthException instead of FirebaseAuthExceptions(extra s is the typo) and if , else should be start with small letter on dart
onPressed: () async {
final email = _email.text;
final password = _password.text;
try {
final userCredential =
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password,
);
print(userCredential);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print("User is not Found");
} else if (e.code == 'wrong password') {
print("Wrong Password");
}
}
},
Use FirebaseAuthException instead of FirebaseAuthExceptions, remove 's'
Good Day!!!

error : display a red line under this statement _userFromFirebaseUser(userCredential.user);

hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
return userCredential != null
? UserModel(
id: userCredential.uid,
bannerImageUrl: '',
name: '',
email: '',
profileImageUrl: '')
: null;
}
Stream<UserModel?> get userCredential {
return auth
.authStateChanges()
.map((userCredential) => _userFromFirebaseUser(userCredential!));
}
Future SignUp(email, password) async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
print("valid");
formdata.save();
try {
UserCredential userCredential =
(await auth.createUserWithEmailAndPassword(
email: myemail!, password: mypassword!));
FirebaseFirestore.instance
.collection('Users')
.doc(userCredential.user!.uid)
.set({'name': email, 'email': email});
_userFromFirebaseUser(userCredential.user);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Navigator.of(context).pop();
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Navigator.of(context).pop();
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
} else {}
}
and the red line appears on this line _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me
userCredential.user is User? not User
change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
return ....
}

Firebase authentication! I'm able to move to home page even if i enter a non registered user

I've successfully added firebase to my flutter2.0 project. I've enables authentication also.I'm able to register a new user also. But the logic to move to home page after authentication is not working. I'm able to login even if I enter a wrong user. I want if I enter proper user then I should navigate to home page, but if the user is not registered it one should not be able to navigate to next page. ie..the basic use of authentication.
But it's not happening here. I'm able to navigate to next place even if I enter wrong user.
Future signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email:email,
password:password,
);
} 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.');
}
}
}
Future newAccount(String email, String password) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e.toString());
}
}
}
//this is how I can this function and try to navigate to next page.
void logMeIn() {
if (formKey.currentState!.validate()) {
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();
}));
});
}
}**strong text**
signInWithEmailAndPassword returns a UserCredential object.
In your logic, you are using .then((value) {...etc})
This value is the result of signInWithEmailAndPassword.
Try changing your logic to this:
authMethods
.signInWithEmailAndPassword(usernameTextEditingContoller.text,
passwordTextEditingContoller.text)
.then((value) {
print('value is: ');
print(value);
if(value.user ==null) return "Error in authentication"; // this will prevent your function form going further down the navigation if the usercredential doesn't have a valid user.
Navigator.of(context)
.pushReplacement(MaterialPageRoute(builder: (context) {
return Home();

Issues with code deprecation saving user info to firebase database

I have codes from former or deprecated flutter version on saving user info to firebase database.
But i have been trying to upgraded the code to the latest firebase_auth package but 'FirebaseUser' is flagged as an error.
void registerUser() async{
final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text).catchError((ex){
//Check Error and display message
PlatformException thisEx = ex;
showSnackBar(thisEx.message);
})).user;
// check if user registration is successful
if(user != null){
DatabaseReference newUserRef = FirebaseDatabase.instance.reference().child('users/${user.uid}');
Map userMap = {
'fullname': fullNameController.text,
'email': emailController.text,
'phone': phoneController.text,
};
newUserRef.set(userMap);
Navigator.pushNamedAndRemoveUntil(context, MainPage.id, (route) => false);
}
}
I have tried upgrading the codes my self but, it doesn't look and behave like before. here is my code but i need some help.
Thanks in advance...
void registerUser() async{
//final UserCredential user = (await _auth.createUserWithEmailAndPassword(email: emailController.text, password: passwordController.text));
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: emailController.text,
password: passwordController.text,
);
if (userCredential != null) {
DatabaseReference newUserRef = FirebaseDatabase.instance.reference()
.child('users/${userCredential.toString}');
M
}
}
on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}