[英]What is the cleanest way to access a logged in Firebase user across your Flutter app?
I am using firebase in my flutter app and accessing the logged in user would be done something like this -我在我的 flutter 应用程序中使用了 firebase,访问登录用户的方式如下 -
Future<FirebaseUser> getLoggedInUser() async {
return await FirebaseAuth.instance.currentUser();
}
I use BLOC and was thinking of adding this to my AuthenticationBloc
class.我使用 BLOC 并考虑将其添加到我的
AuthenticationBloc
类中。 Since this BLOC is injected early, I should be able to access this from anywhere in the app -由于这个 BLOC 是早期注入的,我应该能够从应用程序的任何地方访问它 -
AuthenticationBloc authBloc = BlocProvider.of<AuthenticationBloc>(context);
FirebaseUser user = await authBloc.getLoggedInUser()
But this leads to a few problems like accessing this in a StreamBuilder becomes an issue because of the need of using await which means I would need to make the StreamBuilder async (not sure how).但这会导致一些问题,例如在 StreamBuilder 中访问它会成为一个问题,因为需要使用 await 这意味着我需要使 StreamBuilder 异步(不确定如何)。
What would be the best/cleanest way of accessing the user object FirebaseUser user
from anywhere in the app ?从应用程序的任何位置访问用户对象
FirebaseUser user
的最佳/最干净的方法是什么?
Thanks !谢谢 !
Edit 1 :编辑1:
So one way to do this would be to use a stateful widget every time I want the current user因此,一种方法是在每次需要当前用户时使用有状态小部件
class _MyWidgetState extends State<MyWidget> {
FirebaseUser user;
@override
void initState() {
super.initState();
_updateCurrentUser();
}
void _updateCurrentUser() async {
FirebaseUser currUser = await Firebase.instance.currentUser();
setState(() {
user = currUser;
});
}
But using a stateful widget every time I want the currUser seems weird.但是每次我想要 currUser 时都使用有状态的小部件似乎很奇怪。 Is there a better way out ?
有没有更好的出路?
You can access the user by using stream such as您可以使用流访问用户,例如
StreamBuilder(
stream:FirebaseAuth.instance.onAuthStateChanged,
builder:(context,snapshot){
if (snapshot.connectionState == ConnectionState.active) {
final user = snapshot.data;
return Text("User Id:${user.uid}");
}else{
return Center(
child:CircularProgressIndicator(),
);
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.