Authentication Repository

Jun's Coding Journey·2023년 9월 17일
0

[Learn] Firebase

목록 보기
3/7

An authentication repository in a Flutter application typically abstracts the underlying authentication method or service (like Firebase, REST API, etc.) to provide a consistent and simplified API for the rest of the application. By implementing such a repository, you can decouple the authentication logic from the UI and other parts of your application, which promotes better code organization, reusability, and testability.

class AuthenticationRepository {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  bool get isLoggedIn => user != null;
  User? get user => _firebaseAuth.currentUser;
}

final authRepo = Provider((ref) => AuthenticationRepository());

 

With the repository created, we can check the location of the user and redirect them back to the initial screen if they do not have valid authenticaation.

initialLocation: "/home",
redirect: (context, state) {
  final isLoggedIn = ref.read(authRepo).isLoggedIn;
  if (!isLoggedIn) {
    if (state.subloc != SignUpScreen.routeURL &&
        state.subloc != LoginScreen.routeURL) {
      return SignUpScreen.routeURL;
    }
  }
  return null;
},
profile
Greatness From Small Beginnings

0개의 댓글