我试图弄清楚如何利用 Firebase 的onAuthStateChanges()
流在go_routerrefreshListenable
包的参数中用作可监听,以便在 authState 更改时进行重定向。此外,我正在使用flutter_riverpod进行状态管理。
到目前为止,我的代码如下所示:
我创建了一个简单的 AuthService 类(缩小到最重要的部分):
abstract class BaseAuthService {
Stream<bool> get isLoggedIn;
Future<bool> signInWithEmailAndPassword({ required String email, required String password });
}
class AuthService implements BaseAuthService {
final Reader _read;
const AuthService(this._read);
FirebaseAuth get auth => _read(firebaseAuthProvider);
@override
Stream<bool> get isLoggedIn => auth.authStateChanges().map((User? user) => user != null);
@override
Future<bool> signInWithEmailAndPassword({ required String email, required String password }) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
return true;
} on FirebaseAuthException catch (e) {
...
} catch (e) {
...
}
return false;
}
接下来我创建了这些提供程序:
final firebaseAuthProvider = Provider.autoDispose<FirebaseAuth>((ref) => FirebaseAuth.instance);
final authServiceProvider = Provider.autoDispose<AuthService>((ref) => AuthService(ref.read));
如前所述,我想以某种方式监听这些 authChanges 并将它们传递给路由器:
final router = GoRouter(
refreshListenable: ???
redirect: (GoRouterState state) {
bool isLoggedIn = ???
if (!isLoggedIn && !onAuthRoute) redirect to /signin;
}
)