flutter add user data after google sign in - flutter

i have a problem with save user data to firestore i using sign in with google auth so after i want to add user data to firestore so i can not do this can you help me thanks.
this is my auth code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignProvider extends ChangeNotifier{
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
GoogleSignInAccount? get user => _user;
final FirebaseAuth _auth = FirebaseAuth.instance;
bool result = false;
Future googleLogin()async {
try {
final googleUSer = await googleSignIn.signIn();
if (googleUSer == null ) return;
_user = googleUSer;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final googleAuth = await googleUSer.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
UserCredential userCredential = await _auth.signInWithCredential(credential);
User? user = userCredential.user;
if (user != null){
if (userCredential.additionalUserInfo!.isNewUser) {
await _firestore.collection('users').doc(user.uid).set(
{
'username': user.displayName,
'uid': user.uid,
'profilePhoto': user.photoURL,
}
);
}}
return result;
} catch (e) {
print(e.toString());
}
notifyListeners();
}
Future logout() async {
await googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
}

Hey were you able to save the user to firestore? I have pasted the answer that worked for me.
final userGoogle = FirebaseAuth.instance.currentUser!;
await _firestore
.collection('users')
.doc(cred.user!.uid)
.set({
uid: userGoogle.uid,
name: userGoogle.displayName!,
email: userGoogle.email!,
photoURL: userGoogle.photoURL!,
});
I'm curious if this would mean that every time I login using the google account, the photo from the Google account would overwrite the photoURL, assuming it was updated from let's say the profile page. Could help little insight into it.

Related

Flutter - google_sign_in uses allways previously signed in account

I'm trying to sign in and out using firebase google authentication.
When I hit "Sign in with Google", I can choose the account, but the previous user gets loaded.
This is my code of the class that I'm using to log in and log out:
import 'package:flutter/material.dart';
import "package:google_sign_in/google_sign_in.dart";
import "package:firebase_auth/firebase_auth.dart";
import "package:goouser/global.dart" as global;
import 'package:cloud_firestore/cloud_firestore.dart';
class GoogleLog extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
GoogleSignInAccount get user => _user!;
Future googleLogin() async {
try {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
} on Exception catch (e) {
print(e.toString());
}
notifyListeners();
}
Future logOut() async {
await FirebaseAuth.instance.signOut();
await googleSignIn.disconnect();
}
}
I don't know what I am doing wrong!!

FLUTTER Sign-up/Sign-in with Google popup not appearing

I want to make the user login to the app with google but the pop-up is not coming on the screen. What do I do to make the pop-up appear? When I press on the "Continue with Google" button, it does nothing.
When I debug my code, the debugger straight up goes to the last print statement -
print("GOOGLE SIGN IN: ${googleSignIn.clientId}");
here is my code-
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
part 'google_sign_in_event.dart';
part 'google_sign_in_state.dart';
class GoogleSignInBloc extends Bloc<GoogleSignInEvent, GoogleSignInState> {
GoogleSignInBloc() : super(GoogleSignInInitial()) {
on<GoogleLogInEvent>((event, emit) {
GoogleSignIn googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
// GoogleSignInAccount get user => _user!;
//final googlelogin = MeditationGoogleSignIn().googleLogIn();
Future googleLogIn() async {
try {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) {
print("NO GOOGLE USER");
return null;
}
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
print("THERE IS AN ERROR IN LOGIN: ${e.toString()}");
}
}
print("GOOGLE SIGN IN: ${googleSignIn.clientId}");
});
on<GoogleLogOutEvent>((event, emit) {
Future googleLogOut() async {
final googleSignIn = GoogleSignIn();
await googleSignIn.disconnect();
FirebaseAuth.instance.signOut();
}
});
}
}
Try add scopes: GoogleSignIn(scopes: ['email', 'profile'])

Cannot fit requested classes in a single dex file (# methods: 101809 > 65536) com.android.builder.dexing.DexArchiveMergerException:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:rxdart/rxdart.dart';
import 'homeScreen.dart';
final FirebaseService authService = FirebaseService();
class FirebaseService {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _db = FirebaseFirestore.instance;
`Observable`<User> user;
`Observable`<Map<String, dynamic>> profile;
PublishSubject loading = PublishSubject();
FirebaseService() {
user = `Observable`(_auth.authStateChanges());
profile = user.switchMap((User u) {
if (u != null) {
return _db
.collection('users')
.doc(u.uid)
.snapshots()
.map((snap) => snap.data());
} else {
return `Observable`.just({});
}
});
}
Future<User> googleSignIn(context) async {
loading.add(true);
GoogleSignInAccount googleUser = `await _googleSignIn.signIn()`;
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
final authResult = await _auth.signInWithCredential(credential);
if (authResult.user != null) {
Navigator.pushNamed(context, homeScreen.id);
}
updateUserData(`authResult.user`);
print('signed in' + `authResult.user.displayName`);
loading.add(false);
return `authResult.user`;
}
void updateUserData(User user) async {
DocumentReference ref = _db.collection('users').doc(user.uid);
return ref.set(
{
'uid': user.uid,
'email': user.email,
'photoUrl': user.photoURL,
'displayName': user.displayName,
'lastSeen': DateTime.now(),
},
);
}
void signOut() {
_auth.signOut();
}
}
I used this code before 6 months or more and now I face 9 problems inside this code!!
1- Observable not work and I replaced it with Stream and the problem didn't fix!
2- Inside Future<User> googleSignIn(context) the await _googleSignIn.signIn() show a problem!
3- Also inside Future<User> googleSignIn(context) the
updateUserData(authResult.user); print('signed in' + authResult.user.displayName); loading.add(false); return authResult.user; show a problem!
this is the problems showed the studio code
All required libraries added inside pubspec.yeml and I updated them to the newest version.

adding authenticated user to firestore 'users' collection flutter

I am stuck at the adding an authenticated user to a firestore 'users' collection.
Unhandled Exception: [cloud_firestore/not-found] Some requested document
was not found.
User signs in via Google:
class GoogleSignInProvider extends ChangeNotifier {
final GoogleSignIn _googleSignIn = GoogleSignIn();
GoogleSignInAccount _user;
GoogleSignInAccount get user => _user;
AuthService auth = AuthService();
Future googleSignIn(BuildContext context) async {
try {
final googleUser = await _googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
print(e.toString());
}
final User currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null)
usersRef.add(currentUser.uid);
Navigator.of(context).pushReplacement(
CupertinoPageRoute(builder: (_) => TabScreen()));
notifyListeners();
}
However, no matter what and how I tried the authentication firebase id is not added to the usersRef (the firestore collection). How do I fix it?
My firestore rules are:
match /users/{userId}/{documents=**} {
allow read: if request.auth.uid != null;
allow write, update, create, delete: if isOwner(userId);
}
function isOwner(userId) {
return request.auth.uid == userId;
}
Help appreciated very much!
so this solved my issue:
final User currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null)
await usersRef.doc(currentUser.uid).set({'email':
user.email, 'username': user.displayName, 'photoUrl':
user.photoURL});
I think, I was overthinking it..
Thanks, ppl for the directions and help!
Do this.
Map data = {};
FirebaseFirestore.instance
.collection('usersCollection')
.doc(currentUser.uid)
.set(data);
in place of
usersRef.add(currentUser.uid);
Use set when you have doc id and use add when you want an auto generated id.

i'm not able to get FirebaseUser Method...! alredy add packege Firebse Auth [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;
});
}
}
}