You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firebase Google认证无法持久化,如何维持登录状态?

Hey there, let's fix that persistent auth issue you're facing with Firebase Google Sign-In in your Flutter app. The problem isn't that Firebase isn't storing the session—it's likely that your app isn't checking for an existing authenticated user when it starts up, plus we can make the persistence explicit to be safe. Here's what you need to do:


1. Explicitly Set Firebase Auth Persistence

While Firebase Auth defaults to local persistence, explicitly setting it removes any ambiguity. Update your signInWithGoogle function to include this line before handling the sign-in flow:

Future<String> signInWithGoogle() async {
  // Force local persistence to ensure credentials are saved to the device
  await _auth.setPersistence(Persistence.LOCAL);
  
  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';
}

2. Check Auth Status When the App Starts

Right now, your app opens directly to the login page every time, even if a user is already authenticated. You need to check for an existing user on app launch and redirect accordingly.

Update your app's entry point (e.g., main.dart) to add this check, either with a one-time user lookup or a stream listener for real-time auth state changes:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auth Demo',
      // Use StreamBuilder to listen for auth state changes in real-time
      home: StreamBuilder<FirebaseUser>(
        stream: FirebaseAuth.instance.onAuthStateChanged,
        builder: (context, snapshot) {
          // If user is authenticated, skip login and go home
          if (snapshot.hasData && snapshot.data != null) {
            return const MyHomePage();
          } 
          // Otherwise, show login page
          else {
            return const LoginPage();
          }
        },
      ),
    );
  }
}

3. Fix Your Sign-Out Function

Make sure you're signing out from both Google Sign-In and Firebase Auth to fully clear the session. Add the Firebase Auth sign-out call to your signOutGoogle function:

void signOutGoogle() async{
  await googleSignIn.signOut();
  await _auth.signOut(); // This ensures Firebase clears the local session too
  theID = '';
  print("User Sign Out");
}

Why This Works

  • Explicit Persistence: Telling Firebase to use LOCAL persistence guarantees user credentials are stored on the device, even after the app is closed.
  • Auth State Check: By listening to the auth state stream on app launch, your app automatically redirects to the home page if a valid session exists—no more forced re-logins.
  • Complete Sign-Out: Logging out from both services ensures the session is fully cleared, so the next app launch will correctly show the login page.

内容的提问来源于stack exchange,提问作者JK Ainz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:02:51