我希望我的应用程序的 UI 在我更改有关当前登录的
User
的某些内容时更新,例如更改displayName
属性。如您所见,我正在使用 StreamProvider
和由 Stream<User>
返回的 FirebaseAuth.instance.idTokenChanges()
对象。//Somewhere at the top of my app I have this widget:
class FirebaseAuthWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthHelper.userStream,
initialData: AuthHelper.currentUser,
child: App(),
);
}
}
class AuthHelper {
static final FirebaseAuth _auth = FirebaseAuth.instance;
static User get currentUser => _auth.currentUser;
static Stream<User> get userStream => _auth.idTokenChanges();
//...
static Future<void> updateDisplayName(String newDisplayName) async {
await currentUser.updateDisplayName(newDisplayName);
//TODO how do I get the updated user object (with the updated displayName) to show in UI?
}
//...
}
注意:我已经解决了这个问题,但是有一个解决方法。我想知道的是,有没有更简单、更直接的方法来解决我的问题?
FirebaseAuth.instance.idTokenChanges()
在以下情况下执行,参见文档:
发生以下情况时会触发事件:
- 在听众注册之后。
- 当用户登录时。
- 当前用户注销时。
- 当前用户的token发生变化时
如您所见,这不包括
displayName
属性的变化。但是您可以使用另一种方法,FirebaseAuth.instance.userChanges()
,请参阅documentation。有了这个,您可以听到以下变化:
发生以下情况时会触发事件:
- 在听众注册之后。
- 当用户登录时。
- 当前用户注销时。
- 当前用户的token发生变化时
- 当调用FirebaseAuth.instance.currentUser提供的以下方法时:
- 重新加载()
- 取消链接()
- 更新邮件()
- 更新密码()
- 更新电话号码()
- 更新配置文件()
现在文档似乎已经过时了,因为
updateProfile
在最新版本的 Firebase 工具中已被弃用。弃用警告说:
改用 updatePhotoURL 和 updateDisplayName。
根据OP作者的评论,确认是在执行
userChanges
时调用了updateDisplayName
,所以解决了问题。在你的代码中,而不是这个:
static Stream<User> get userStream => _auth.idTokenChanges();
使用这个:
static Stream<User> get userStream => _auth.userChanges();