flutter firebase login not redirect after signInWithCredential - firebase

I'm using flutter and firebase auth with google sign in.
specifically I'm referring to this Tutorial
but, in that case no redirect after login success.
in my case, i want to redirect after login success.
I have made like this on AuthService
Future<FirebaseUser> googleSignIn() async {
loading.add(true);
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
FirebaseUser user = await _auth.signInWithCredential(credential);
updateUserData(user);
print("signed in : " + user.displayName);
loading.add(false);
return user;
}
initState
void initState() {
super.initState();
authService.profile.listen((state) {
print("ini statenya $state");
});
}
and button
CupertinoButton(
color: const Color(0xFFdd4b39),
child: const Text('Google'),
onPressed: () => authService.googleSignIn().then((user) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BeforeDashboard(
uuid: user,
)),
);
})),
But, it only work when i use debug mode. and not redirect on release mode.
After choose account popup will be gone but not redirect on dashboard

Related

The method 'getCredential' isn't defined for the type 'PhoneAuthProvider'

As far as I can see, there are numerous deprecated methods in flutter firebase authentication.
here is my code;
FlatButton(
child: Text("Confirm"),
textColor: Colors.white,
color: Colors.blue,
onPressed: () async {
FirebaseAuth _auth = FirebaseAuth.instance; // I didn't use it here. I did for you to see
final code = _codeController.text.trim();
final AuthCredential credential = PhoneAuthProvider.getCredential(
verificationId: verificationId, smsCode: code);
UserCredential result =
await _auth.signInWithCredential(credential);
User user = result.user;
if (user != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
HomeScreen(user: user)));
} else {
print("Error");
}
},
)
I try to do phone auth but getCredential has error. I looked at firebase documentation. it says that PhoneAuthProvider deprecated and I should use PhoneAuthCredential with getCredential. I used it but it didn't work. I saw that there are various question about this error on stackoverflow but I can't find workaround yet
This is how I implemented it in my app on firebase_auth: ^0.18.0+1:
#override
Future<void> signInWithSmsCode(String smsCode) async {
final AuthCredential authCredential = PhoneAuthProvider.credential(
smsCode: smsCode,
verificationId: _verificationCode,
);
try {
await auth.signInWithCredential(authCredential);
} on PlatformException catch (e) {
throw _firebaseErrorFactory.getException(e.code);
} on FirebaseAuthException {
throw _firebaseErrorFactory
.getException('ERROR_INVALID_VERIFICATION_CODE');
}
}

How to signout of Google auth in firebase Flutter?

These are my login and logout functions using firebase auth in flutter,The sign is working perfectly but the signout is not working, I tried to print the 'signout text' in debug console and its printing but then the navigation to SignIn page part is not working.
Future<FirebaseUser> signInWithGoogle() async {
try{GoogleSignInAccount googleUser = await _googleSignIn.signIn();
// Step 2
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential cred= GoogleAuthProvider.getCredential(idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
FirebaseUser user = (await _auth.signInWithCredential(cred)).user;
return user;} catch(e){
print(e.toString());
return null;
}
}
signOutGoogle() async{
await _auth.signOut();
await _googleSignIn.signOut();
print('signed out');
}
This is my signout button implementation:
FlatButton.icon(
onPressed: () async => {
Navigator.pushNamed(context, '/signin'),
_auth.signOutGoogle(),
},
icon: Icon(Icons.exit_to_app),
label: Text(
'Sign out',
style: GoogleFonts.abel(color: Colors.black),
),
)
switch the 2 methods and await the signOutGoogle():
onPressed: () async {
await _auth.signOutGoogle(),
Navigator.pushNamed(context, '/signin'),
},

how to login once and stay logged in until you log out?

I couldn't figure it out. as i restart the app (if i am signed in or not) it goes to the login page, can you guys help me out on this. i am new to flutter so detailed instructions will be appreciated. Thanks
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: (googleSignIn.isSignedIn() != null) ? MainPage() : LoginPage(),
routes: {
'upload': (context) => ItemInput(),
'toyota': (context) => Toyota(),
},
));
}
Auth.dart
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<User> signInWithGoogle() async {
final GoogleSignInAccount googleSignInAcount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAcount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleSignInAuthentication.idToken,
accessToken: googleSignInAuthentication.accessToken);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final User currentUser = _auth.currentUser;
assert(currentUser.uid == user.uid);
return user;
}
void signOutGoogle() async {
await googleSignIn.signOut();
}
Login.dart
void click() {
signInWithGoogle().then((user) => {
this.user = user,
Navigator.push(
context, MaterialPageRoute(builder: (context) => MainPage()))
});
}
RaisedButton.icon(
onPressed: () async {
click();
},
label: Text(
'Sign-up with Google ',
)),
Firebase automatically restores the user's authentication state when the app is restarted. So you'd typically detect whether the user is already signed in, and then navigate to the post-login screen when they are.
According to the documentation on authentication state you can get the authentication state with:
FirebaseAuth.instance
.authStateChanges()
.listen((User user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
// ... navigate to post-login screen
}
});
One way to do it is by using shared preference, see, https://pub.dev/packages/shared_preferences
When the signin is successful do,
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isLoggedIn", true);
This will store a boolean value that you use to check if the user is signed in or not. It will be saved even after the app is closed unless you uninstall or clear app data.
and in the main.dart use that stored prefs value to check if the user is already signed in or not by doing -
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isLoggedIn = prefs.getBool("isLoggedIn");
Use the isLoggedIn value, navigate the user to either Login Screen or Home Screen, and use it to perform other logic.

When I log out of application and again login it takes me to homepage automatically without asking for choosing an account

I have created login application, using flutter and firebase.
i am doing google login. I have 2 pages login.dart and homepage.dart where everything happens. When i click on login button it asks for choose an account and take me to homepage, but when i logout, and again try to login it takes me automatically to homepage, but i want it to ask again for choosing an account.
I have created signout() function in loginpage itself, where I have written the code for the rest of the authentication, but when I call this function in homepage.dart in logout button, it wont come.
Code for Login Authentication in loginpage.dart
class _LoginPageState extends State<LoginPage> {
String _email;
String _password;
//google sign in
final GoogleSignIn googleSignIn= GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> _signIn() async{
//GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
GoogleSignInAccount googleUser = await googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
final FirebaseUser user = await _auth.signInWithCredential(credential);
print("User Name: ${user.displayName}");
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _auth.currentUser();
assert(user.uid == currentUser.uid);
Navigator.of(context).pushReplacementNamed('/homepage');
}
Future<void> signOut() async {
return googleSignIn.signOut();
}
code for log out button in homepage.dart
MaterialButton(
onPressed: () {
signOut
FirebaseAuth.instance.signOut().then((value) {
Navigator.of(context).pushReplacementNamed('/landingpage');
})
.catchError((e){
print(e);
});
},
child: Text('Log Out'),
)
Please Help me out

Flutter Authentication sign in & sign out with Google from logged screen to login screen

today I tried to build 2 screens "login with GG" and "logout redirect to login screen". Succeed! But when I log in again, Previous gg account logged in immediately without requiring sign-in popup. On my device remember logged account. How to sign out completely and sign-in again with the other accounts. Here my code:
I have 'the home page with login with google' and 'home-center page with signout button'. Besides, I have api.dart to log in and log out, and the main page using routes to 2 pages.
- Main Page:
routes: {
"home-page": (context) => MyHomePage(),
"game-center": (context) => GameCenterPage(),
},
home: MyHomePage(),
- Api.dart:
class FBApi {
static FirebaseAuth _auth = FirebaseAuth.instance;
static GoogleSignIn _googleSignIn = GoogleSignIn();
FirebaseUser firebaseUser;
FBApi(FirebaseUser user) {
this.firebaseUser = user;
}
static Future<FBApi> signInWithGoogle() async {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final FirebaseUser user = await _auth.signInWithGoogle(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
assert(user.email != null);
assert(user.displayName != null);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await _auth.currentUser();
assert(user.uid == currentUser.uid);
return FBApi(user);
}
static Future<void> signOut() async {
await _auth.signOut().then((_) {
print("***** log out...what the hell?");
// Navigator.of(context).pushNamedAndRemoveUntil("/login",
ModalRoute.withName("/home"));
});
}
}
- gameCenter.dart:
onPressed: () async {
_signOut();
Navigator.of(context).pushNamedAndRemoveUntil("home-page", ModalRoute.withName("game-center"));
},
- home.dart
class MyHomePage extends StatelessWidget {
Future<bool> _loginUser() async {
final api = await FBApi.signInWithGoogle();
if (api != null) {
return true;
} else {
return false;
}
}
...
I experienced a similar issue this weekend and resolved it by also signing out of GoogleSignIn - however I'm not sure if this is the correct approach as I would have expected FirbaseAuth to auto sign out of all providers.
static Future<void> signOut() async {
await _auth.signOut().then((_) {
//try the following
_googleSignIn.signOut();
//try the following
Navigator.of(context).pushNamedAndRemoveUntil("/login", ModalRoute.withName("/home"));
});
if you are having issue with the login popup for Google SignIn do this after signout call
Navigator.pushReplacement(
(context), MaterialPageRoute(builder: (context) => widget));
User gets signed out from Firebase, but not from Google.
So next time you already have a user signed in and that is returned by GoogleSignIn().
You need to sign out from Google as well. Following works perfectly for me:
Future signOut() async {
try {
await _fireBaseAuthInstance.signOut();
await _googleSignInInstance.signOut();
} catch (e) {
print('Failed to signOut' + e.toString());
}
}

Resources