Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist user Auth Flutter Firebase

Tags:

I am using Firebase Auth with google sign in Flutter. I am able to sign in however when I close the app(kill it), I have to sign up all over again. So is there a way to persist user authentication till specifically logged out by the user? Here is my auth class

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

class Auth {
  FirebaseAuth _firebaseAuth;
  FirebaseUser _user;

  Auth() {
    this._firebaseAuth = FirebaseAuth.instance;
  }

  Future<bool> isLoggedIn() async {
    this._user = await _firebaseAuth.currentUser();
    if (this._user == null) {
      return false;
    }
    return true;
  }

  Future<bool> authenticateWithGoogle() async {
    final googleSignIn = GoogleSignIn();
    final GoogleSignInAccount googleUser = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth =
    await googleUser.authentication;
    this._user = await _firebaseAuth.signInWithGoogle(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    if (this._user == null) {
      return false;
    }
    return true;
    // do something with signed-in user
  }
}

Here is my start page where the auth check is called.

import 'package:flutter/material.dart';
import 'auth.dart';
import 'login_screen.dart';
import 'chat_screen.dart';

class Splash extends StatefulWidget {

  @override
  _Splash createState() => _Splash();
}

class _Splash extends State<Splash> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CircularProgressIndicator(
          value: null,
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _handleStartScreen();
  }

  Future<void> _handleStartScreen() async {
    Auth _auth = Auth();
    if (await _auth.isLoggedIn()) {
      Navigator.of(context).pushReplacementNamed("/chat");
    }
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => LoginScreen(auth: _auth,)));
  }
}
like image 743
Ayush Singh Avatar asked Jan 31 '19 21:01

Ayush Singh


People also ask

How do I set Firebase persistence?

For Android and Apple platforms, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false . For the web, offline persistence is disabled by default. To enable persistence, call the enablePersistence method.


2 Answers

I believe your problem is routing. In my apps I use FirebaseAuth and it works just as you say you wanted to, and I don't persist any login token. However, I don't know why your approach of using a getUser is not working.

Try to adjust your code to use onAuthStateChanged.

Basically, on your MaterialApp, create a StreamBuilder listening to _auth.onAuthStateChanged and choose your page depending on the Auth status.

I'll copy and paste parts of my app so you can have an idea:

[...]

final FirebaseAuth _auth = FirebaseAuth.instance;

Future<void> main() async {
  FirebaseApp.configure(
    name: '...',
    options:
      Platform.isIOS
        ? const FirebaseOptions(...)
        : const FirebaseOptions(...),
    );

  [...]  

  runApp(new MaterialApp(
    title: '...',
    home: await getLandingPage(),
    theme: ThemeData(...),
  ));
}

Future<Widget> getLandingPage() async {
  return StreamBuilder<FirebaseUser>(
    stream: _auth.onAuthStateChanged,
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData && (!snapshot.data.isAnonymous)) {
        return HomePage();
      }

      return AccountLoginPage();
    },
  );
}
like image 179
Feu Avatar answered Sep 20 '22 00:09

Feu


Sorry, it was my mistake. Forgot to put the push login screen in else.

  Future<void> _handleStartScreen() async {
    Auth _auth = Auth();
    if (await _auth.isLoggedIn()) {
      Navigator.of(context).pushReplacementNamed("/chat");
    }
    else {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => LoginScreen(auth: _auth,)));
    }
  }
like image 41
Ayush Singh Avatar answered Sep 22 '22 00:09

Ayush Singh