简体   繁体   中英

Flutter web issue with persistence session in firebase auth after page refresh

I recently upgraded Flutter SDK to v3.0.5 and built a login interface for Flutter web connecting it with Firebase authentication using Email. Login, logout and signup are all successfully working (ie routing to the correct pages).

But while log in, and upon refreshing the web page / hot reload during debugging, the session is lost and page routes back to login page.

I tried checking if the current user is null using those two methods:

Method 1:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    User? user = FirebaseAuth.instance.currentUser;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: user == null ? LoginPage() : HomePage(),
    );
  }
}

Method 2:

class _LoginPageState extends State<LoginPage> {
  TextEditingController? emailText = TextEditingController();
  TextEditingController? passwordText = TextEditingController();
  User? user = FirebaseAuth.instance.currentUser;

  @override
  void initState() {
    super.initState();
    FirebaseAuth.instance.authStateChanges().listen((user) {
      if (user != null) {
        Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage(),
            ));
      }
    });
  }

Also tried using Firebase persistence session method, and am not sure if this is the right way to call it from a button onPressed:

      ElevatedButton(
        child: Text('Login'),
        onPressed: () async {
          try {
            await FirebaseAuth.instance
                .signInWithEmailAndPassword(
                    email: emailText!.text,
                    password: passwordText!.text)
                .then((value) async {
              await FirebaseAuth.instance
                  .setPersistence(Persistence.SESSION)
                  .then((_) async {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => HomePage(),
                    ));
              });
            });
          } on FirebaseAuthException catch (e) {
            print(e.message.toString());
          } catch (e) {
            print(e.toString());
          }
        },
      ),

Yet non of the above works.

Additionally, I also encountered that the Firebase.initializeApp throws back exceptions after refreshing, related to

"FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created

  • call Firebase App.initializeApp() (app/no-app).

Error1 Error2

The installation of Firebase was done similar to the steps mentioned in the documentation in main.dart and index.html as well.

NOTE: I replicated the same codes in a previous project I worked on last year which was working fine without any problems.

Have you tried updating packages to the newest versions?

According to this answer , these versions fixed the problem: firebase_core: ^1.20.0 firebase_auth: ^3.6.0 cloud_firestore: ^3.4.1

A fix that worked for me was to make sure when debugging I use:

flutter run -d chrome --web-port=50000 (or whatever port you like).

By default web apps will clear all their data between runs, adding a port stops this. (maybe the port is randomly generated and the data is keyed to that port)

You should also make sure its not an async issue and use:

final user = await FirebaseAuth.instance.authStateChanges().first;

Instead of just trying to grab the user property ( FirebaseAuth.instance.currentUser ) which might not have had a chance to be populated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM