简体   繁体   English

Firebase 验证用户信息 stream

[英]Firebase auth user information stream

I have a profile page the shows the user his currently registered email and an edit icon that takes him to the page where he can edit the email.我有一个个人资料页面,向用户显示他当前注册的 email 和一个编辑图标,将他带到他可以编辑 email 的页面。 When the user changes the email successfully, he is returned to the previous page that showed him the registered email.当用户成功更改 email 后,他会返回到上一页,显示已注册的 email。

I want the user to see the new email.我希望用户看到新的 email。 But the user keeps seeing the old email until the page is reloaded.但是用户一直看到旧的 email 直到页面重新加载。

So my first thought was to naturally replace the FutureBuilder with StreamBuilder.所以我的第一个想法是自然而然地将 FutureBuilder 替换为 StreamBuilder。 I was not sure how to get a stream of the current user and not the future, so I used the only stream I know for FirebaseUser --> onAuthStateChanged我不确定如何获得当前用户的 stream 而不是未来,所以我使用了我所知道的 FirebaseUser 唯一的 stream --> onAuthStateChanged

  Widget buildEmail() {
    return StreamBuilder(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting)
          return Center(
              child: SpinKitRing(
            color: Colors.white,
            size: 30,
          ));
        else if (snapshot.hasError)
          return Center(child: Text(snapshot.error));
        else {
          // final email = snapshot.data.data['email'];
          final email = snapshot.data.email;
          return Padding(
            padding: const EdgeInsets.only(left: 25.0),
            child: Text('$email', style: TextStyle(color: Colors.black)),
          );
        }
      },
    );
  }

This StreamBuilder behaves identically to the FutureBuilder I had before这个 StreamBuilder 的行为与我之前的 FutureBuilder 相同

  Widget buildEmail() {
    return FutureBuilder(
      future: FirebaseAuth.instance.currentUser(),
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting)
          return Center(
              child: SpinKitRing(
            color: Colors.white,
            size: 30,
          ));
        else if (snapshot.hasError)
          return Center(child: Text(snapshot.error));
        else {
          // final email = snapshot.data.data['email'];
          final email = snapshot.data.email;
          return Padding(
            padding: const EdgeInsets.only(left: 25.0),
            child: Text('$email', style: TextStyle(color: Colors.black)),
          );
        }
      },
    );
  }
}

So I looked into the documentation of onAuthStateChanged and it states:所以我查看了 onAuthStateChanged 的文档,它指出:

  /// Receive [FirebaseUser] each time the user signIn or signOut

This lead me to check on my update email method and check if my user is being signed in again to the app.这导致我检查我的更新 email 方法并检查我的用户是否再次登录到应用程序。

static Future<void> updateEmail(String password, String newEmail, BuildContext context) async {
    final user = await CurrentUser.getCurrentUser();
    final ref = Firestore.instance.collection('users');

    try {
      AuthCredential credential = EmailAuthProvider.getCredential(email: user.email, password: password);
      AuthResult result = await user.reauthenticateWithCredential(credential);  // Sign in?
      result.user.updateEmail(newEmail);
      ref.document(user.uid).updateData({'email': newEmail});
      Navigator.of(context).pop();
      Fluttertoast.showToast(msg: 'Success!');
    } on PlatformException catch (error) {
      print(error);
      changeEmailErrorDialog(context, error: error.message);
    } catch (error) {
      print(error);
      changeEmailErrorDialog(context, error: error);
    }
  }

I think that I am signing in the user since this method prevents the ERROR_REQUIRES_RECENT_LOGIN exception我认为我正在登录用户,因为这种方法可以防止ERROR_REQUIRES_RECENT_LOGIN异常

  AuthResult result = await user.reauthenticateWithCredential(credential);  // Sign in?

Am I doing something wrong?难道我做错了什么? How can I get a stream of the user?如何获得用户的 stream? The Firebase method for obtaining the current user returns a future获取当前用户的Firebase方法返回一个future

FirebaseAuth.instance.currentUser();

Shouldn't there be a stream version of this method?这种方法不应该有 stream 版本吗?

There is a stream version of it;它有一个 stream 版本;

FirebaseAuth.instance.userChanges(),

Example;例子;

StreamBuilder<User>(
              stream: FirebaseAuth.instance.userChanges(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                }
                return Text(snapshot.data.displayName);
              },
            ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM