return boolean in async function in flutter - firebase

I want to check if a user exists after login. I wrote the code below:
checkIfUserExists() async {
await Firebase.initializeApp();
FirebaseAuth.instance.authStateChanges().listen((User? user) {
if (user == null) {
print('User is currently signed out!');
return false;
} else {
print('User is signed in!');
return true;
}
});
}
The function can't return a boolean because it isn't a void as expected by the function. I need (to get the date from firebase authentication) a async function. Is there a way to get a return boolean from my function above?

The authStateChanges() method returns a Stream, while an async method must return a Future.
Given the name checkIfUserExists, it seems you only care about the current value, in which case it's easier to use the currentUser property instead:
checkIfUserExists() async {
await Firebase.initializeApp();
var user = FirebaseAuth.instance.currentUser;
if (user == null) {
print('User is currently signed out!');
return false;
} else {
print('User is signed in!');
return true;
}
}
If you call this code while the app is just started, currentUser may still be nil, as Firebase checks the user's credentials again at this point. If you want to wait for Firebase to finish this check, and get the user after that, you can get the first event from the authStateChanges() stream:
checkIfUserExists() async {
await Firebase.initializeApp();
var user = await FirebaseAuth.instance.authStateChanges().first();
if (user == null) {
print('User is currently signed out!');
return false;
} else {
print('User is signed in!');
return true;
}
}

bool checkUserExist()=>FirebaseAuth.instance.currentUser!=null;

Related

The getter 'uid' not defined

i'm trying to create a food track app on android studio, it's my first time and i'm working with firebase_auth 3.3.12. my code in the aut.dart is:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_firstapp/models/user_model.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
AuthService();
// create user object based on FirebaseUser.
UserModel _userFromUser(User) {
return user != null ? UserModel(uid: user.uid) : null;
}
// auth change user stream
Stream<UserModel> get user {
return _auth.authStateChanges()
.map(_userFromUser);
}
Future<UserModel> getUser() async {
User user = await _auth.currentUser();
return _userFromUser(user);
}
// sign in with email and password
Future signInWithEmailAndPassword(String email, String password) async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return _userFromUser(user);
} catch(e) {
print(e.toString());
return null;
}
}
// sign up with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user;
// create a new user document in database
return _userFromUser(user);
} catch(e) {
print(e.toString());
return null;
}
}
// sign out
Future signOut() async {
try {
return await _auth.signOut();
} catch(e){
print(e.toString());
return null;
}
}
}
However i'm getting 2 errors:
-The getter 'uid' isn't defined for the type 'Stream';
-The expression "await _auth.currentUser()" doesn't evaluate to a function, so it can't be invoked.
How can i rewrite the code? thanks
The _auth.currentUser is not a function (it used to be, but changed about a year ago), but rather a property. It also isn't asynchronous, so you don't need await nor to return a Future.
So:
UserModel getUser() {
User user = _auth.currentUser;
return _userFromUser(user);
}
In this code, your argument is capitalised ('User') but in the code block you write 'user'.
UserModel _userFromUser(User) {
return user != null ? UserModel(uid: user.uid) : null;
}
Furthermore, for _auth.currentUser(), you do not need to use await as it does not return a future.

Showing: Ignoring header X-Firebase-Locale because its value was null, when I call user.reload()

I am facing this problem when I call the method reload() from FB Auth: Ignoring header X-Firebase-Locale because its value was null.
The authentication system is working fine.
The code below is called after the createUserWithEmailAndPassword method, in another page.
User user = FirebaseAuth.instance.currentUser;
Future<void> checkEmailVerified() async {
print(user.emailVerified);
print(user.uid);
await user.reload();
if (user.emailVerified) {
print('ok');
timer.cancel();
Get.offAll(() => HomePage(), binding: HomeBinding());
}
}
#override
void initState() {
controller.user.sendEmailVerification();
timer = Timer.periodic(Duration(seconds: 5), (timer) {
user.reload();
checkEmailVerified();
});
FirebaseAuth.instance.authStateChanges().listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});
super.initState();
}
Same clicking in the email verifying, the emailVerified variable doesn't change to the true.
The issue appears when the code call the reload() method.
I already searched for all, but I can't get solved this issue.
The login and the signup system is work fine. The user is registered in the FB Authentication console.
I would like the implementing email verify in my app
Regards,

How does firebase passwordless authentication work with dynamic link for a flutter app?

When I click on verification link from my email , it opens my app running in background but didChangeAppLifecycleState method returns data as null and deepLink as set in firebase instead of the whole emailLink from my email, resulting in SignInWithEmailAndLink to fail as its supposed to match email address entered in widget from the link recieved.
Here's the code taken from this article https://medium.com/firebase-developers/dive-into-firebase-auth-on-flutter-email-and-link-sign-in-e51603eb08f8 :-
1.didChangeAppLifecycleState method
#override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.resumed) {
final PendingDynamicLinkData data =
await FirebaseDynamicLinks.instance.getInitialLink();
if( data?.link != null ) {
handleLink(data?.link);
}
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink `enter code here`= dynamicLink?.link;
handleLink(deepLink);
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
});
}
}
handleLink method
void handleLink(Uri link) async {
if (link != null) {
final User user = (await _auth.signInWithEmailAndLink(
email: _userEmail,
link: link.toString(),
))
.user;
if (user != null) {
setState(() {
_userID = user.uid;
_success = true;
});
} else {
setState(() {
_success = false;
});
}
} else {
setState(() {
_success = false;
});
}
setState(() {});
}
main method (initializing firebase)
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Note: - Deeplink is a concept still new to me in flutter, so I have set it randomly in firebase. My register page has a WidgetsBindingObserver to help resume app lifecycle state. My signup and sign in code is in an email widget and I'm not using forms to validate my textfields.
it seems that after you signin with email link the firebase instance has been not updated before checking auth.SigninWithEMailLink() you need to update it in firebase instance like this
var user= await auth.currentUser();
await user.reload();
user=await auth.currentUser();
if still you are facing problem please provide some more code to let me understand your issue properly

Firebase/Flutter: reload() not refreshing user.isEmailVerified

I'm sending a verification link when a user registers in the app, but when I try to create a stream that listens for when the user has clicked the verify link in the email.
I'm aware that I somehow need to refresh the user token, but I can't seem to get it to work. I thought reload() method was the one, but maybe I'm just not implementing it correctly.
The problem is that the Stream always returns isEmailVerified == false, only way to make it true is for the user to log out and log in again, which is something I'd like to avoid. How do I do this?
I've created this future:
//CHECKS IF EMAIL IS VERIFIED
Future<bool> checkIfEmailIsVerified() async {
FirebaseUser currUser = await _auth.currentUser();
await currUser.reload();
currUser = await _auth.currentUser();
final bool flag = currUser.isEmailVerified;
if (currUser != null) {
return flag;
} else {
return false;
}
}
and this stream:
//IS EMAILVERIFIED STREAM
Stream<EmailVerified> get emailVerified async* {
final bool isEmailVerified = await checkIfEmailIsVerified();
yield EmailVerified(isEmailVerified);
}
Unfortunately it's necessary to get fresh instance of the user after reload:
User user = FirebaseAuth.instance.currentUser;
if (user != null) {
await user.reload();
user = FirebaseAuth.instance.currentUser;
if (user.emailVerified) {
...
}
}
Try using a single await over chained futures
FirebaseUser currUser = await _auth.currentUser().then((u) => u.reload().then((_) => _auth.currentUser()));
final bool flag = currUser.isEmailVerified;

How to get user id from firebase auth as string?

I'm trying to insert data to firestore with the authenticated user id as the document id but i got null from the parameter.
Please take a look at my script.
void didChangeDependencies() {
uid = '';
super.didChangeDependencies();
}
Future _fetchUID() async {
var auth = AuthProvider.of(context).auth;
return await auth.getCurrentUser().then((user) => _uid = user.uid);
}
_validateAndSubmit() async {
setState(() {
_errorMessage = '';
_isLoading = true;
});
if (_validateAndSave()) {
try {
_fetchUID();
await Report.create(_uid, _suspectName, _plateNumber, _civilizationId,
_drivingLicenseId, _clause, _description);
return Navigator.of(context).pop();
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = e.message;
});
print(_errorMessage);
throw Exception(e);
}
}
}
In this method below you can see that I have already tried to set the _uid, but I still cannot get the _uid value.
Future _fetchUID() async {
var auth = AuthProvider.of(context).auth;
return await auth.getCurrentUser().then((user) => _uid = user.uid);
}
This is how the getCurrentUser() method looks like.
Future<FirebaseUser> getCurrentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user;
}
Am I doing it wrong?
First of all, you mixed the Future.then syntax and the async await syntax.
You should probably write your method this way:
void _fetchUID() async {
var auth = AuthProvider.of(context).auth;
_uid = (await auth.getCurrentUser()).uid;
}
If _uid is still null for you after calling _fetchUID this way, then you are simply not signed in, meaning that there is no FirebaseUser as you first need to sign in.
In your _validateAndSubmit method, you also first need to await your _fetchUID call, otherwise it will pass _uid before it has been assigned a value.
...
try {
await _fetchUID();
await Report.create(_uid, ..);
...

Resources