Skip to content

Instantly share code, notes, and snippets.

@felangel
Created August 4, 2019 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felangel/953f7c5a6f9e7e091d43d951ac4ef951 to your computer and use it in GitHub Desktop.
Save felangel/953f7c5a6f9e7e091d43d951ac4ef951 to your computer and use it in GitHub Desktop.
[flutter_firestore_todos] authentication bloc
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:user_repository/user_repository.dart';
import 'package:flutter_firestore_todos/blocs/authentication_bloc/bloc.dart';
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
final UserRepository _userRepository;
AuthenticationBloc({@required UserRepository userRepository})
: assert(userRepository != null),
_userRepository = userRepository;
@override
AuthenticationState get initialState => Uninitialized();
@override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
if (event is AppStarted) {
yield* _mapAppStartedToState();
}
}
Stream<AuthenticationState> _mapAppStartedToState() async* {
try {
final isSignedIn = await _userRepository.isAuthenticated();
if (!isSignedIn) {
await _userRepository.authenticate();
}
final userId = await _userRepository.getUserId();
yield Authenticated(userId);
} catch (_) {
yield Unauthenticated();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment