Auth Stream Listen to the current Firebase user

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.
Get Unlimited PRO Access

OR


*Enrollment provides full access to this course (and updates) for life.

Auth Service

Create a file named auth.dart in the services directory.

file_type_flutter services/auth.dart
import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final userStream = FirebaseAuth.instance.authStateChanges();
  final user = FirebaseAuth.instance.currentUser;
}

Listen to Current User

Use the home page to render a different set of UI elements based on the user’s auth state in Firebase. If the user is signed in, show the topics screen. If the user is not signed in, show the login screen.

file_type_flutter home.dart
import 'package:flutter/material.dart';
import 'package:quizapp/login/login.dart';
import 'package:quizapp/shared/shared.dart';
import 'package:quizapp/topics/topics.dart';
import 'package:quizapp/services/auth.dart';

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: AuthService().userStream,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LoadingScreen();
        } else if (snapshot.hasError) {
          return const Center(
            child: ErrorMessage(),
          );
        } else if (snapshot.hasData) {
          return const TopicsScreen();
        } else {
          return const LoginScreen();
        }
      },
    );
  }
}

Login Screen

Update the login screen with a Scaffold.

file_type_flutter main.dart
class LoginScreen extends StatelessWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Login'),
        ),
    );
  }
}

Q&A Chat