0
votes

I'm creating an app using Firebase google authentication in Flutter. I was able to sign in to the app, but when I close the app, the authentication is removed which required me to sign in again.

This is my login screen, 'Sign in with Google' button will trigger the onPressed() in _signInButton().

import 'package:flutter/material.dart';
import 'package:auth_screen/sign_in.dart';
import 'package:auth_screen/homepage.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image(image: AssetImage("assets/thelogo.jpg"), height: 200.0),
              SizedBox(height: 25),
             _signInButton(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _signInButton() {
    return OutlineButton(
      splashColor: Colors.grey,
      onPressed: () {
        signInWithGoogle().whenComplete(() {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) {
                return MyHomePage();
              },
            ),
          );
      });
      },
     shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: Colors.grey),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(image: AssetImage("assets/google_logo.png"), height: 35.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with Google',
                style: TextStyle(
                  fontSize: 20,
                  color: Colors.grey,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

This is the page where all Google and Firebase perform authentication.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();

String name;
String email;
String imageUrl;

Future<String> signInWithGoogle() async {

  final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  final AuthResult authResult = await _auth.signInWithCredential(credential);
  final FirebaseUser user = authResult.user;

  imageUrl = user.photoUrl;

  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);

  //return 'signInWithGoogle succeeded: $user';
}

void signOutGoogle() async{
  await googleSignIn.signOut();
  theID = '';
  print("User Sign Out");
}

I heard that by default Firebase will persist user auth, but it doesn't happen in my program. Is there any method for making the user authentication persist until I press the log out button? Please let me know if you have any ideas.

1

1 Answers

1
votes

Firebase does store persist auth, you just need to call it!!

There are two ways to approach this:

  1. Without Shared_pref - In this method, you create a splash screen, which is the entry point of your app(add app logo or something here) and in that where you check if a user is logged in then send him to the main screen or else send him to the login screen.
Future<void> _handleStartScreen() async {
    Auth _auth = Auth();

    if (await _auth.isLoggedIn()) {
      Navigator.popAndPushNamed(context, HomeScreen.id);
    } else {
      Navigator.popAndPushNamed(context, WelcomeScreen.id);
    }
  }

You can call it from initstate of the splash screen.

2.With Shared_pref:- this is the more commonly used way. In this, you store auth state locally in-app with the use of a package shared_preferences(https://pub.dev/packages/shared_preferences#-readme-tab-, you can check how to use it from the given link) So whenever a user logs in, store a bool in it with logged_in = true, and whenever the app starts you call the instance of shared_preferences from your splash screen. you can toggle the logged_in var when he logs out.