Persist user Auth Flutter Firebase

核能气质少年 提交于 2020-06-22 09:47:08

问题


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,)));
  }
}

回答1:


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();
    },
  );
}



回答2:


You can use shared_preferences to keep alive your session even when you kill the app. Here is the documentation https://pub.dartlang.org/packages/shared_preferences.

Also I've heard that it's possible to use sqlite to persist the session.




回答3:


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,)));
    }
  }


来源:https://stackoverflow.com/questions/54469191/persist-user-auth-flutter-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!