Issue when updating Firebase in Flutter App with current user - firebase

I just updated Google Firebase Auth in Flutter app because I was getting some wried SDK errors but now I'm getting
Error: 'currentUser' isn't a function or method and can't be invoked.
var user = await _firebaseAuth.currentUser();
I looked at the migration guide and understand that currentUser() is now synchronous via the currentUser getter. but I'm not sure how I should change my code now to fix this.
My code
class Auth implements BaseAuth {
final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;
#override
Future<String> signIn(String email, String password) async {
var result = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
var user = result.user;
return user.uid;
}
#override
Future<String> signUp(
String email, String password, String name, String company) async {
final userReference = FirebaseDatabase.instance.reference().child('users');
var result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
var user = result.user;
await userReference
.child(user.uid)
.set(User(user.uid, email, name, company).toJson());
return user.uid;
}
#override
Future<auth.User> getCurrentUser() async {
var user = await _firebaseAuth.currentUser();
return user;
}
#override
Future<void> signOut() async {
return _firebaseAuth.signOut();
}
#override
Future<void> sendEmailVerification() async {
var user = await _firebaseAuth.currentUser();
await user.sendEmailVerification();
}
#override
Future<void> resetPassword(String email) async =>
await _firebaseAuth.sendPasswordResetEmail(email: email);
#override
Future<bool> isEmailVerified() async {
var user = await _firebaseAuth.currentUser();
return user.isEmailVerified;
}
}

It looks like you're using the latest version of the FlutterFire libraries with outdated code.
In previous versions of the libraries, currentUser() was a method, that you had to await. In the latest versions of the library it's a property, and you no longer have to await its result.
So
var user = _firebaseAuth.currentUser;
Also see the documentation on using Firebase Authentication in your Flutter app, specifically the section on monitoring authentication state as it provides a way to listen for updates to the authentication state.

Related

How to access the uid of a google-registered user for our Firestore collection?

I am creating a flutter app. The point is that in my database, I want the users to be recognized with their uid. For users registered with email & password, there is no problem because I can easily access to their uid with user.uid. But when the user registers with his google account, I don't know how to access to his uid. I just know how to access to his id which is different by running _user.id. How to access the user's uid in this case? Here's the code:
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
// create user object based on firebase user
Users? _userFromFirebaseUser(User? user) {
return user != null ? Users(uid: user.uid) : null;
}
// auth change user stream
Stream<Users?> get user {
return _auth.authStateChanges().map(_userFromFirebaseUser);
}
//register with email & psswrd
Future registerWithEmailAndPassword(String email, String password) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
await DatabaseService(uid: user!.uid).updateUserData('new user', 0);
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
Future signInithGoogle() async {
try {
final result = await googleSignIn.signIn();
if (result == null)
return await DatabaseService(uid: _user!.id)
.updateUserData('new user', 0);
_user = result;
final googleAuth = await result.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
} catch (e) {}
}
The 'updateUserData' function creates a new record for the user when he registers. The DatabaseService class contains all the functions related to Firestore. here it is:
class DatabaseService {
final String uid;
DatabaseService({required this.uid});
// collection reference
final CollectionReference userCollection =
FirebaseFirestore.instance.collection('users');
Future updateUserData(String name, int points) async {
return await userCollection.doc(uid).set({
'name': name,
'points': points,
});
}
}
When you call await _auth.signInWithCredential(credential), you get back a UserCredential, which is the same that you get back from await FirebaseAuth.instance.signInWithEmailAndPassword(...).
So you can get the UID from the UserCredential in both cases with:
var credentials = await _auth.signInWithCredential(credential);
var uid = credentials.user!.uid
If you're listening to auth state changes, then that will fire when you sign in with any provider, and you'll get a User? object. So you can get the UID from that with:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User ${user.uid} is signed in!');
}
});

FirebaseUser not an existing class | authentication errors [duplicate]

I'm new to Flutter. I have an Issue with Firebase Auth/ Google Auth
The FirebaseUser is not defined
Code:
FirebaseAuth _auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
Future<FirebaseUser> currentUser() async { // The Issue is here in the Future<>
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.getCredential(
idToken: authentication.idToken, accessToken: authentication.accessToken);
final AuthResult authResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user; // and here as I can't define this FirebaseUser object to return
return user;
}
Pubspec.yml
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
firebase_auth: ^0.18.0
location: ^3.0.2
page_transition: ^1.1.6
google_sign_in: ^4.5.1
flutter_facebook_login: ^3.0.0
firebase_database: ^4.0.0
I also face the same issue with AuthResult
final AuthResult authResult = await _auth.signInWithCredential(credential);
Starting from Version firebase_auth 0.18.0:
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredential. Therefore change your code to the following:
Future<User> currentUser() async {
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.credential(
idToken: authentication.idToken,
accessToken: authentication.accessToken);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
return user;
}
FirebaseUser changed to User
AuthResult changed to UserCredential
GoogleAuthProvider.getCredential() changed to GoogleAuthProvider.credential()
onAuthStateChanged which notifies about changes to the user's sign-in state was replaced with authStateChanges()
currentUser() which is a method to retrieve the currently logged in user, was replaced with the property currentUser and it no longer returns a Future<FirebaseUser>.
Example of the above two methods:
FirebaseAuth.instance.authStateChanges().listen((event) {
print(event.email);
});
And:
var user = FirebaseAuth.instance.currentUser;
print(user.uid);
Deprecation of UserUpdateInfo class for firebaseUser.updateProfile method.
Example:
Future updateName(String name, FirebaseUser user) async {
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await user.updateProfile(userUpdateInfo);
await user.reload();
}
now
import 'package:firebase_auth/firebase_auth.dart' as firebaseAuth;
Future updateName(String name, auth.User firebaseUser) async {
firebaseUser.updateProfile(displayName: name);
await firebaseUser.reload();
}
Since firebase_auth 0.18.0, the class FirebaseUser was changed to User
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredentail. Therefore change FirebaseUser to User
The class FirebaseUser was changed to User
try this way
_registerUser() async {
try {
final User? user =
(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailCtrl.text,
password: passCtrl.text,
))
.user;
FirebaseFirestore.instance.collection('users').doc().set({
'name': nameCtrl.text,
'uid': user!.uid,
'email': user.email,
'isEmailVerified': user.emailVerified, // will also be false
'photoUrl': user.photoURL, // will always be null
});
print("Created");
} catch (e) {
print(e.toString());
}
}
Run
flutter pub get
Then rebuild your app.
This can be your signin function with email and password as of Sept 2020.Initialze app is a new introduced method we must at least call once before we use any other firebase methods.
Future<void> signin() async {
final formState = _formkey.currentState;
await Firebase.initializeApp();
if (formState.validate()) {
setState(() {
loading = true;
});
formState.save();
try {
print(email);
final User user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password))
.user;
} catch (e) {
print(e.message);
setState(() {
loading = false;
});
}
}
}

Display error message instead of throw exception in console (Flutter Firebase)

How to show the error message when the user enters the incorrect username and password? Can I display a message when there are multiple conditions in authenticating the user? The message should show on the screen instead of throwing the exception in the console.
The exception I get in the console
The exception has occurred.
PlatformException (PlatformException(firebase_auth, com.google.firebase.auth.FirebaseAuthInvalidUserException: There is no user record corresponding to this identifier. The user may have been deleted., {code: user-not-found, additionalData: {}, message: There is no user record corresponding to this identifier. The user may have been deleted.}, null))
import 'package:firebase_auth/firebase_auth.dart';
abstract class BaseAuth {
Future<String> currentUser();
Future<String> signIn(String email, String password);
Future<String> createUser(String email, String password);
Future<void> signOut();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Future<String> signIn(String email, String password) async {
UserCredential result = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return user.uid;
}
Future<String> createUser(String email, String password) async {
UserCredential result = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
User user = result.user;
return user.uid;
}
Future<String> currentUser() async {
User user = _firebaseAuth.currentUser;
return user != null ? user.uid : null;
}
Future<void> signOut() async {
return _firebaseAuth.signOut();
}
}
A simple try catch would do the trick
Future<String> signIn(String email, String password) async {
try{
UserCredential result = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
User user = result.user;
return user.uid;
}on AuthException catch(error){
return Future.error(error);
}
}
Now on how to handle the error in the UI assuming you know the basics :D
await signIn(email,password).then((onSuccess){
//do something with data or not up to you
}).catchError((err){
print(err);
});
Hope it helps :)

Firebase can not change displayName ,displayName is null on every way

Can't add I more user information with await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: _email, password: _password); function?
part of signup.dart file:
String _email, _password, _name;
final formkey = new GlobalKey<FormState>();`
Future<void> registered() async {
if (formkey.currentState.validate()) {
formkey.currentState.save();
try {
await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: _email, password: _password);
FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
Firestore.instance
.collection("users")
.document(firebaseUser.uid)
.setData({"name": _name});
await firebaseUser.reload();
firebaseUser = await FirebaseAuth.instance.currentUser();
print(
"${firebaseUser.uid},${firebaseUser.email},${firebaseUser.displayName} , $_password this user has been created-----");
} catch (e) {
print("${e.message} message--------------------------------------");
}
} else {
print("somthing went wrong");
}
}
I have tried many way to do this but still i have no result
You are saving data in Firestore, and trying to get the name from Firebase Auth. Those are two services. Instead of trying to use firestore, what you could is,
FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = _name;
firebaseUser.updateProfile(userUpdateInfo);
await firebaseUser.reload();
firebaseUser = await FirebaseAuth.instance.currentUser();
After creating the account using the method .createUserWithEmailAndPassword pass the value of the user to another class by
final FirebaseAuth _auth = FirebaseAuth.instance;
//user object based on firebase
User _userFromFirebase(FirebaseUser user){
return user != null ? User(uid: user.uid):null;
}
Future loginWithEmailAndPass(String email,String password)async{
try{
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return _userFromFirebase(user);
}catch(e){
print(e.toString());
return null;
}
}
Pass the value of user to a new class by creating a new dart file
class User{
final String uid;
User({this.uid});
}
Include that dart file in the home page for the user name.
Refer this tutorial for guidance.
https://youtu.be/Jy82t4IKJSQ?list=PL4cUxeGkcC9j--TKIdkb3ISfRbJeJYQwC

flutter question: why is this giving me a bunch or errors? below is my code and errors

errors
- Target of URI doesn't exist: 'package:firebase_auth/firebase_auth.dart'.
Try creating the file referenced by the URI, or Try using a URI for a file that does exist.dart(uri_does_not_exist
The name 'FirebaseUser' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'FirebaseUser'.dart(non_type_as_type_argument)
code:
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
abstract class BaseAuth {
Future<String> signIn(String email, String password);
Future<String> signUp(String email, String password);
Future<FirebaseUser> getCurrentUser();
Future<void> sendEmailVerification();
Future<void> signOut();
Future<bool> isEmailVerified();
}
class Authen implements BaseAuth {
final Auth _firebaseAuth = Auth.instance;
Future<String> signIn(String email, String password) async {
AuthResult result = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
return user.uid;
}
Future<String> signUp(String email, String password) async {
AuthResult result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
return user.uid;
}
Future<FirebaseUser> getCurrentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user;
}
Future<void> signOut() async {
return _firebaseAuth.signOut();
}
Future<void> sendEmailVerification() async {
FirebaseUser user = await _firebaseAuth.currentUser();
user.sendEmailVerification();
}
Future<bool> isEmailVerified() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user.isEmailVerified;
}
}
You're getting the first error because the package wasn't properly installed. You can try a few things:
flutter packages get (to use the packages in pubspec.yaml)
restarting your IDE
flutter clean and then flutter run (clears build cache)
flutter packages pub cache repair (pub cache might be corrupted)
The second error will resolve itself once the package is correctly installed. Because 'package:firebase_auth/firebase_auth.dart' doesn't exist, you can't use any classes from that package. FirebaseUser is a class in the firebase_auth package.

Resources