Flutter Firebase:如何在 UI 中更新用户

问题描述 投票:0回答:1

我希望我的应用程序的 UI 在我更改有关当前登录的

User
的某些内容时更新,例如更改
displayName
属性。如您所见,我正在使用
StreamProvider
和由
Stream<User>
返回的
FirebaseAuth.instance.idTokenChanges()
对象。
有没有办法让我手动(我的意思是从我的代码)向该流添加一个新事件,以便应用程序的整个 UI 更新?

//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?
  }

  //...

}

注意:我已经解决了这个问题,但是有一个解决方法。我想知道的是,有没有更简单、更直接的方法来解决我的问题?

flutter firebase firebase-authentication stream stream-builder
1个回答
0
投票

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();
© www.soinside.com 2019 - 2024. All rights reserved.