CodeBlanks Logo Icon CodeBlanks

authStateChanges

Listen to session changes with authStateChanges.

What is authStateChanges?

The authStateChanges method returns a Stream<User?> that fires events whenever the auth state changes. When the user signs in, a User is emitted; on sign-out, null is emitted. It also emits the current state once on startup, making it ideal for session monitoring.

auth.authStateChanges().listen((user) {
  print(user?.email ?? 'misafir');
});

Listening to the stream

When you listen to the stream with listen, the callback is called on every auth change. Inside this callback you perform side effects such as navigation, snackbars, or widget updates. It can also be used with StreamBuilder for automatic rebuilds.

auth.authStateChanges().listen((user) {
  if (user == null) {
    // giriş ekranına git
  } else {
    // ana ekrana git
  }
});

Practice Listen to the state stream

Get the auth instance, listen to the authStateChanges stream with listen. Print 'yok' if user is null. Wait 10 milliseconds after starting to listen.

Starter code

main.dart
class User {
  final String email;
  User(this.email);
}

class FirebaseAuth {
  static final FirebaseAuth instance = FirebaseAuth._();
  FirebaseAuth._();
  User? _user;

  Stream<User?> authStateChanges() async* {
    yield _user;
  }
}

void main() async {
  // durum akışını dinle
  // kullanıcı null ise 'yok' yazdır
  // 10ms bekle
}

Sample solution

main.dart
class User {
  final String email;
  User(this.email);
}

class FirebaseAuth {
  static final FirebaseAuth instance = FirebaseAuth._();
  FirebaseAuth._();
  User? _user;

  Stream<User?> authStateChanges() async* {
    yield _user;
  }
}

void main() async {
  final auth = FirebaseAuth.instance;
  auth.authStateChanges().listen((user) {
    print(user?.email ?? 'yok');
  });
  await Future.delayed(Duration(milliseconds: 10));
}

Expected output

yok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does authStateChanges return?

  • Future<User?>
  • User?
  • Stream<User?> Correct answer
  • Widget

Explanation: authStateChanges returns a Stream<User?>; a new value is emitted whenever the auth state changes.

2 Listen to the state stream

Question
auth.____().listen((user) {
  print(user?.email);
});
Answer
auth.authStateChanges().listen((user) {
  print(user?.email);
});

Explanation: authStateChanges returns the stream that fires when the auth state changes; it is listened to with listen.

3 authStateChanges parts

Term Meaning
authStateChanges State change stream
Stream<User?> Return type
listen Listens to the stream
User? null when no session

All lessons in Advanced