0

The official docs for Firebase Authentication for Flutter mentions this code to check whether user is logged in or not:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

Docs also mention that Firebase must be initialized before anything else so I have added the initialization code to main.dart:

class MyApp extends StatelessWidget {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          // Handle error
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return AuthState();
        }
        return CircularProgressIndicator();
      },
    );
  }
}

AuthState is where I want to manage the authentication state. I have added it in the same file.

class AuthState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auth',
      home: FirebaseAuth.instance.authStateChanges().listen((User user) {
        if (user == null) {
          return SignupScreen();
        } else {
          return HomeScreen();
        }
      }),
    );
  }
}

The above code does not work because home expects a widget and authStateChanges returns StreamSubscription so how to make it work? I want to redirect to signup screen if user is not authenticated and to the home screen if user is.

1 Answer 1

1

You could use a StreamBuilder to consume the stream of authentication state changes.

import 'package:flutter/material.dart';

class AuthWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

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

class _AuthWidgetState extends State<AuthWidget> {
  Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          if (snapshot.data == null) {
            return SignupScreen();
          } else {
            return HomeScreen();
          }
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}
2
  • Thanks. Getting another error that no firebase app has been initialized, call firebase initialize and the error causing widget is AuthState. Auth State is in a future so it should only trigger once the initialization is complete?
    – gegobyte
    Commented Dec 25, 2020 at 9:13
  • Could you try moving the Firebase app initialization to the main function similar to the example here and let me know if that makes any difference?
    – tnc1997
    Commented Dec 25, 2020 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.