why Flutter login with facebook is not working - flutter

I'm trying to make a login screen with Facebook but end up with this error when I run my code. here is my code:
import 'package:facebook_login/services/auth_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
import 'package:auth/auth.dart';
class AuthBloc {
final authService = AuthService();
final fb = FacebookLogin();
Stream<User> get currentUser => authService.currentUser;
loginFacebook() async {
print('Starting Facebook Login');
final res = await fb.logIn(
permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email
]
);
switch(res.status){
case FacebookLoginStatus.Success:
print('It worked');
//Get Token
final FacebookAccessToken fbToken = res.accessToken;
//Convert to Auth Credential
final AuthCredential credential
= FacebookAuthProvider.getCredential(accessToken: fbToken.token);
//User Credential to Sign in with Firebase
final result = await authService.signInWithCredentail(credential);
print('${result.user.displayName} is now logged in');
break;
case FacebookLoginStatus.Cancel:
print('The user canceled the login');
break;
case FacebookLoginStatus.Error:
print('There was an error');
break;
}
}
logout(){
authService.logout();
}
}
when i run this i get this error message
Invalid depfile: C:\Users\Main\OneDrive\stuff\Documents\seltech\st\.dart_tool\flutter_build\7b28b646cfa2e7424746c78d0801893a\kernel_snapshot.d
Error: Couldn't resolve the package 'facebook_login' in 'package:facebook_login/services/auth_service.dart'.
Error: Couldn't resolve the package 'auth' in 'package:auth/auth.dart'.
lib/src/bloc/auth_bloc:1:8: Error: Not found: 'package:facebook_login/services/auth_service.dart'
import 'package:facebook_login/services/auth_service.dart';
there are more errors that pop up.
if you need more of the code I can send some more of it
it's so much it won't fit in here
all of the error I get is from the auth_block. I have another login page made on a separate screen.
I also have a manual login with firebase auth there .

With these packages on the pubspec:
flutter_facebook_auth: ^3.5.1
firebase_auth: ^3.1.0
firebase_core: ^1.6.0
And this function:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<String?> facebookSignin() async {
try {
final _instance = FacebookAuth.instance;
final result = await _instance.login(permissions: ['email']);
if (result.status == LoginStatus.success) {
final OAuthCredential credential =
FacebookAuthProvider.credential(result.accessToken!.token);
final a = await _auth.signInWithCredential(credential);
await _instance.getUserData().then((userData) async {
await _auth.currentUser!.updateEmail(userData['email']);
});
return null;
} else if (result.status == LoginStatus.cancelled) {
return 'Login cancelled';
} else {
return 'Error';
}
} catch (e) {
return e.toString();
}
}
I'm able to login with facebook on my app
don't forget to also follow the configuration steps for android/ios and facebook for developers console

enter image description here
#enable this Permissions and features
then it will work

Related

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'])

I'm trying to implementation Facebook SDK using Firebase but I keep getting an error on the when I copy this code in the correct spot

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:29.0.1')
// Add the dependency for the Firebase SDK for Google Analytics
// When using the BoM, don't specify versions in Firebase dependencies
implementation 'com.google.firebase:firebase-analytics'
// Add the dependencies for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
implementation 'com.facebook.android:facebook-android-sdk:latest.release'
}
}
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
abstract class AuthBase{
User get currentUser;
Stream<User> authStateChanges();
Future<User>signInAnonymously();
Future<User> signInWithGoogle();
Future<void>signOut();
}
class Auth implements AuthBase {
final _firebaseAuth = FirebaseAuth.instance;
Stream<User> authStateChanges() => _firebaseAuth.authStateChanges();
#override
User get currentUser => _firebaseAuth.currentUser;
#override
Future<User> signInAnonymously() async {
final userCredential = await _firebaseAuth.signInAnonymously();
return userCredential.user;
}
#override
Future<User> signInWithGoogle() async{
final googleSignIn = GoogleSignIn();
final googleUser = await googleSignIn.signIn();
if(googleUser !=null) {
final googleAuth = await googleUser.authentication;
if (googleAuth.idToken != null) {
final userCredential = await _firebaseAuth.signInWithCredential(
GoogleAuthProvider.credential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
));
return userCredential.user;
} else {
throw FirebaseAuthException(
code:'ERROR_MISSING_GOOGLE_ID_TOKEN',
message:'Missing Google ID Token',
);
}
}
else {
throw FirebaseAuthException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user'
);
}
}
Future<User> signInWithFacebook() async{
final fb = FacebookLogin();
}
#override
Future<void> signOut() async {
final googleSignIn = GoogleSignIn();
await googleSignIn.signOut();
await _firebaseAuth.signOut();
// TODO: implement signOut
throw UnimplementedError();
}
}
`]1][1][I'm trying to implement facebook SDK into my project.I have followed all of the steps up to this point and you can find the link below but I'm still getting an error When I copied this code in to the Main activity page.What am I doing wrong?I posted my auth.dart file and the dependencies as well
package com.example.time_trackerpractice
import io.flutter.embedding.android.FlutterActivity
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
class MainActivity: FlutterActivity() {
}
The problem that you have (see image) its because you don't have any flutter packages related to facebook auth.
In this line of your code you are try instance a FacebookLogin, but doesn't exits any import related to facebook login.
final fb = FacebookLogin();
You can use this package to facebook login (flutter_facebook_auth), and replace your inside code of your function signInWithFacebook for this:
Future<User> signInWithFacebook() async {
final result = await FacebookAuth.instance
.login(permissions: ['email', 'public_profile']);
final accessToken = result.accessToken;
final credential = FacebookAuthProvider.credential(accessToken.token);
userCredential = await _firebaseAuth.signInWithCredential(credential);
return userCredential.user
}

Google Authentication and Facebook Authentication Existing User

Hello Everyone someone please offer me some help if you can. I'm not sure if this is an issue on Firebase's side or if I failed on my code or configuring the Firebase authentication correctly.
So here's the issue.
I wanted to see if a user existed inside the firestore. If it does then link the accounts. I read the documentation and understand that when using the SigninwithCredential() it should throw an error saying something on the lines of "ERROR USER ALREADY EXISTS IN FIRESTORE".
So testing went something like this to see if I'd get an error before trying to handle the error.
Continue with Facebook (OK).
Signed In (OK).
Continue with Google (Expected Error) (Didn't throw Error)
So what happened here instead was the user originally created by Facebook was overridden by Google.
Sign In with Facebook (Expected Error) (OK) Recieved error as expected "An Account already exists but with different sign-in credentials"
Read documentation several times and compared google code with Facebook code and can't seem to find answer.
class MyFirebase {
static bool isSignIn = false;
static auth.FirebaseAuth _auth = auth.FirebaseAuth.instance;
static FacebookLogin facebookLogin = FacebookLogin();
static GoogleSignIn googleSignIn = GoogleSignIn();
static Future<auth.User> loginGoogle() async {
final prefs = await SharedPreferences.getInstance();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
if (googleSignInAccount == null) {
print("ERROR HAS OCCURED WITH THE GOOGLE LOGIN");
throw new Exception("ERROR HAS OCCURED WITH THE LOGIN");
} else {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
var item = googleSignInAccount.photoUrl;
print("PHOTO URL" + item);
prefs.setString("photoURL", item);
final auth.AuthCredential credential = auth.GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken);
try {
var authResult = await _auth.signInWithCredential(credential);
return authResult.user;
} catch (e) {
print(e);
throw (e);
}
}
}
static Future<auth.User> loginFacebook() async {
final FacebookLoginResult result = await facebookLogin.logIn(['email']);
final prefs = await SharedPreferences.getInstance();
var a;
switch (result.status) {
case FacebookLoginStatus.cancelledByUser:
print("CANCELLED BY USER DO NOT RETURN");
throw new Exception("CANCELLED BY USER DO NOT RETURN");
break;
case FacebookLoginStatus.error:
print("ERROR OCCURED");
throw new Exception("ERROR oCCURED");
break;
case FacebookLoginStatus.loggedIn:
try {
final FacebookAccessToken accessToken = result.accessToken;
auth.AuthCredential credential =
auth.FacebookAuthProvider.credential(accessToken.token);
print("########## MAKING GRAPH RESPONSE");
final response = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,first_name,picture.width(800).height(800),last_name,email&access_token=${accessToken.token}');
final profile = jsonDecode(response.body);
String item = profile['picture']['data']['url'];
prefs.setString("photoURL", item);
a = await _auth.signInWithCredential(credential);
return a.user;
} catch (e) {
print(e);
throw e;
}
break;
}
return null;
}
static Future<void> signOut() async {
await facebookLogin.logOut();
await _auth.signOut();
await googleSignIn.signOut();
}
}
**strong text** ```

Flutter Facebook Login Error: Getter not found: 'Success'. case FacebookLoginStatus.Success

I am using Flutter to make my app and I wish to do function login with Facebook and this is what I did:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
abstract class AuthBase {
User get currentUser;
Stream<User> authStateChanges();
Future<User> signInWithFacebook();
Future<void> signOut();
}
class Auth implements AuthBase {
final _firebaseAuth = FirebaseAuth.instance;
#override
Stream<User> authStateChanges() => _firebaseAuth.authStateChanges();
#override
User get currentUser => _firebaseAuth.currentUser;
#override
Future<User> signInWithFacebook() async {
final fb = FacebookLogin();
final response = await fb.logIn(permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email,
]);
switch (response.status) {
case FacebookLoginStatus.Success:
final accessToken = response.accessToken;
final userCredential = await _firebaseAuth.signInWithCredential(
FacebookAuthProvider.credential(accessToken.token),
);
return userCredential.user;
case FacebookLoginStatus.Cancel:
throw FirebaseAuthException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
case FacebookLoginStatus.Error:
throw FirebaseAuthException(
code: 'ERROR_FACEBOOK_LOGIN_FAILED',
message: response.error.developerMessage,
);
default:
throw UnimplementedError();
}
}
#override
Future<void> signOut() async {
final facebookLogin = FacebookLogin();
await facebookLogin.logOut();
await _firebaseAuth.signOut();
}
}
And this is error I got:
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
lib/services/auth.dart:68:32: Error: Getter not found: 'Success'.
case FacebookLoginStatus.Success:
^^^^^^^
lib/services/auth.dart:74:32: Error: Getter not found: 'Cancel'.
case FacebookLoginStatus.Cancel:
^^^^^^
lib/services/auth.dart:79:32: Error: Getter not found: 'Error'.
case FacebookLoginStatus.Error:
^^^^^
Restarted application in 278ms.
I tried to look at the tutorial and I see no difference in the code I wrote, it is on Udemy so I can not copy the link down here to you. Please tell me how to deal with that, thank you so much and have a good day
change code to
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
abstract class AuthBase {
User get currentUser;
Stream<User> authStateChanges();
Future<User> signInWithFacebook();
Future<void> signOut();
}
class Auth implements AuthBase {
final _firebaseAuth = FirebaseAuth.instance;
#override
Stream<User> authStateChanges() => _firebaseAuth.authStateChanges();
#override
User get currentUser => _firebaseAuth.currentUser;
#override
Future<User> signInWithFacebook() async {
final fb = FacebookLogin();
final response = await fb.logIn(permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email,
]);
switch (response.status) {
case FacebookLoginStatus.success:
final accessToken = response.accessToken;
final userCredential = await _firebaseAuth.signInWithCredential(
FacebookAuthProvider.credential(accessToken.token),
);
return userCredential.user;
case FacebookLoginStatus.cancel:
throw FirebaseAuthException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
case FacebookLoginStatus.error:
throw FirebaseAuthException(
code: 'ERROR_FACEBOOK_LOGIN_FAILED',
message: response.error.developerMessage,
);
default:
throw UnimplementedError();
}
}
#override
Future<void> signOut() async {
final facebookLogin = FacebookLogin();
await facebookLogin.logOut();
await _firebaseAuth.signOut();
}
}
lower case this code:
case FacebookLoginStatus.Success: to case FacebookLoginStatus.success:
case FacebookLoginStatus.Cancel: to case FacebookLoginStatus.cancel:
case FacebookLoginStatus.Error: to case FacebookLoginStatus.error:
Please try this snippet of code, It's working fine for me.
fbSignIn() async {
var facebookLogin = FacebookLogin();
var facebookLoginResult = await facebookLogin.logIn(['email']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
//showToast(msg: "A Error Occured");
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
//showToast(msg: "Login Cancelled");
break;
case FacebookLoginStatus.loggedIn:
print(facebookLoginResult.accessToken.token);
print("LoggedIn");
break;
}
}

Issue with the Firebase database and Page Routing

I am new with flutter and got stuck with an issue. In my code the scenario is:
first it authenticate the user through phone and otp verification.
After successful verification it must check if the logged in user has profile in the database.
If the user profile is available the flag is set to true and then it must route it to the dashboard page
or
If the user profile is not available it must route first to User Profile page to create a profile and then route it to database.
i had written the same condition.On execution as their is user profile in the database still it is routing to User Profile page.
I am also providing the screenshot of the database and the console part.
Code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:udharibook/Screens/SignInPage.dart';
import 'package:udharibook/Screens/UserProfile.dart';
import 'package:udharibook/Screens/dashboard.dart';
class AuthService {
bool flag = false;
final FirebaseAuth _auth = FirebaseAuth.instance;
final DBRef = FirebaseDatabase.instance.reference().child('Users');
handleAuth(){
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext, snapshot){
if(snapshot.hasData){
readData();
print(flag);
if(flag ==true)
return DashboardPage();
else
return UserProfile();
}
else {
return SignIn();
}
},
);
}
void readData() async {
final FirebaseUser user = await _auth.currentUser();
final userid = user.uid;
DBRef.child(userid).once().then((DataSnapshot data){
print(userid);
if(data.value!=null)
{
flag = true;
print(data.key);
print(data.value);
}
else{
print('User not found');
flag = false;
}
});
}
signOut(){
FirebaseAuth.instance.signOut();
}
signIn(AuthCredential authCreds){
FirebaseAuth.instance.signInWithCredential(authCreds);
}
signInWithOTP(smsCode,verId){
AuthCredential authCreds = PhoneAuthProvider.getCredential(
verificationId: verId,
smsCode: smsCode
);
signIn(authCreds);
}
}
I would suggest you to move your flag variable to a global file and then try it. I guess since I dont know what those print statements say.