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(),
          );
        }
      },
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.