In flutter, how can I “merge” Firebase onAuthStateChanged with user.getTokenId() to return a Stream?

為{幸葍}努か 提交于 2021-01-29 13:41:55

问题


In flutter, I'm trying to access Custom Claims to decide which Widget I will show, I was able to get the user as Stream and convert it to a Class doing:

  Stream<User> get user {
return _auth.onAuthStateChanged
 .map(_userFromFirebaseUser);
  }


 User _userFromFirebaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

I would like to add the user.getIdToken() claims['role'] to the User object (i.e.: User(uid: user.uid, role: token.claims['role']), but I'm not sure how to merge a Future into a Stream resulting in a Stream.


回答1:


There is an "operator" for this problem. It is called asyncMap. It almost has the same functionality as map except you can pass an async function as the argument.

Stream<User> get user {
  return _auth.onAuthStateChanged.asyncMap(_userFromFirebaseUser);
}

Future<User> _userFromFirebaseUser(FirebaseUser user) async {
  final tokenResult = await user.getIdToken();

  return user != null ? User(uid: user.uid, role: tokenResult.claims['role']) : null;
}


来源:https://stackoverflow.com/questions/60742877/in-flutter-how-can-i-merge-firebase-onauthstatechanged-with-user-gettokenid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!