skip to Main Content

Im still new in Flutter , I wanted to know how to redirect to another page after login to my app using google sign in, can anyone help in this matter? Heres the code. Im not sure where to redirect to another page in this case. Thank you

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleSignInProvider extends ChangeNotifier {
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

  Future googleLogin() async{
    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);
    notifyListeners();
  }
}

4

Answers


  1. The method FirebaseAuth.instance.signInWithCredential returns a Future(Promise) and it can either be that the user successfully signed in or not.

    final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
    final user = userCredential.user;
    

    If you want to move to a difference screen, you can just use Navigator.push method:

    Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => //YOUR SCREEN HERE),
      );
    

    Documentation

    Login or Signup to reply.
  2. Firebase auth offers a authStateChanges() which is a Stream, so every time a new user logs in or logged out, it will get triggered, in your code, calling:

    await FirebaseAuth.instance.signInWithCredential(credential);
    

    will trigger it if it ran successfully.

    you can listen to that authStateChanges() stream by using a StreamBuilder like in this example:

    StreamBuilder<User>(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.active) {
              User user = snapshot.data;
              if (user == null) {
                return LoginPage();
              }
              return HomePage();
            } else {
              return Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }
          },
        );
    

    This widget should run on a top level of your app ( as an example using it in the home of the MaterialApp of your app)

    initially, when there is no user logged in, the firebase’s User will be null, so it will redirect to the LoginPage

    on a successfully logged-in operation such as the FirebaseAuth.instance.signInWithCredential(credential); in your code, the User will have some data and it will not be null, so the StreamBuilder will get notified, and show the HomePage() page.

    Login or Signup to reply.
  3. Here’s what I did with mine

    class Authentication {
        static Future<User?> signInWithGoogle() async {
        FirebaseAuth auth = FirebaseAuth.instance;
        User? user;
    
        final GoogleSignIn googleSignIn = GoogleSignIn();
    
        final GoogleSignInAccount? googleSignInAccount =
    await googleSignIn.signIn();
    
    if (googleSignInAccount != null) {
      final GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount.authentication;
    
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );
    
      try {
        final UserCredential userCredential =
        await auth.signInWithCredential(credential);
    
        user = userCredential.user;
      } on FirebaseAuthException catch (e) {
        if (e.code == 'account-exists-with-different-credential') {
          Get.showSnackbar(const GetSnackBar(
            message: "You already have an account with this email. Use other login method.",
            duration: Duration(seconds: 3),
          ));
        }
        else if (e.code == 'invalid-credential') {
          Get.showSnackbar(const GetSnackBar(
            message: "Invalid Credential!",
            duration: Duration(seconds: 3),
          ));
        } else if (e.code == 'wrong-password') {
          Get.showSnackbar(const GetSnackBar(
            message: "Wrong password!",
            duration: Duration(seconds: 3),
          ));
        }
      } catch (e) {
        Get.showSnackbar(const GetSnackBar(
          message: "Unknown Error. Try again later",
          duration: Duration(seconds: 3),
        ));
      }
    }
    
    return user;
      }
    }
    

    then in the login screen you could add this to navigate if you logged in successfully:

    import 'your/google/sign/in/provider.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    
    class Login {
        User? user;
        user = await Authentication.signInWithGoogle();
        if (user != null) {
          Navigator.pushReplacement<void, void>(
        context,
        MaterialPageRoute<void>(
          builder: (BuildContext context) => const PageAfterSignIn(),));
        } else {
          
        }
    }
    

    I write mine based on this article

    Login or Signup to reply.
  4. You can go to next screen as below code after click on google login button from login page

    onTap: () async {
                GoogleSignInProvider. googleLogin().then((isSuccess) {
                  if (isSuccess) {
                    Navigator.pushReplacement(context,
                        MaterialPageRoute(builder: (context) => HomePage()));
                  }
                });
              },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search