[英]check authentication state of User using FirebaseAuth in Flutter
I know a question like this exists but it is filled with outdated and incorrect answers.我知道存在这样的问题,但它充满了过时和不正确的答案。 The new FlutterFire docs use Streams to get the state of the User and I had a hard time, trying to perform such a trivial task because I am inexperienced with Flutter and Dart.新的FlutterFire文档使用 Streams 来获取用户的状态,我很难尝试执行如此微不足道的任务,因为我对 Flutter 和 Dart 缺乏经验。 Here is the answer and ref of the outdated question.这是过时问题的答案和参考。
I am expecting an answer along with StreamBuilder, and here is the code I have written up till now:我期待与 StreamBuilder 一起得到答案,这是我迄今为止编写的代码:
@override
Widget build(BuildContext context) {
return StreamBuilder(
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if(snapshot.hasData) {
print("data exists");
return snapshot.data ? First() : SignIn();
}
else {
return SignIn();
}
},
future: isUserLoggedIn(),
);
}
Stream<bool> isUserLoggedIn() {
FirebaseAuth.instance
.authStateChanges()
.listen((User user) {
if (user == null) {
print('User is currently signed out!');
// return false; ???
} else {
print('User is signed in!');
// return true; ???
}
});
}
EDIT:编辑:
Firebase Auth enables you to subscribe in realtime to this state via a >Stream. Firebase 身份验证使您能够通过 >Stream 实时订阅此状态。 Once called, the stream provides an immediate event of the user's >current authentication state, and then provides subsequent events whenever ?the authentication state changes.一旦被调用,流提供用户>当前认证状态的即时事件,然后每当认证状态改变时提供后续事件。
isUserLoggedIn()
isn't returning a stream of any kind. isUserLoggedIn()
不返回任何类型的流。 I recommend just listening to the actual authStateChanges()
stream.我建议authStateChanges()
实际的authStateChanges()
流。
Widget build(BuildContext context) {
return StreamBuilder<User>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
if(snapshot.hasData) {
print("data exists");
return First();
}
else {
return SignIn();
}
},
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.