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;
},