简体   繁体   English

Flutter - 如何使用 Firebase Auth 在 streambuilder 中访问未来的价值

[英]Flutter - how to access the value of a future inside a streambuilder, with Firebase Auth

I am using Firebase Authentication for a subscription-based app that I am building and using cloud functions and custom claims, I am ensuring that the user can only log in if they have an active subscription.我正在为我正在构建的基于订阅的应用程序使用 Firebase 身份验证并使用云功能和自定义声明,我确保用户只有在有有效订阅的情况下才能登录。

My app has a landing page, which checks to see if the user is logged in and if they are, they are taken to the app home page.我的应用程序有一个登录页面,用于检查用户是否已登录,如果已登录,他们将被带到应用程序主页。 If not, they are shown the login screen.如果没有,他们将显示登录屏幕。 This is the code for it:这是它的代码:

class LandingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthBase>(context, listen: false);
    return StreamBuilder<User?>(
        stream: auth.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            User? user = snapshot.data;
            user?.reload();
            user = snapshot.data;

            if (user == null || user.emailVerified == false) {
              return SignInHomePage.create(context);
            }
            return Provider<User?>.value(
              value: user,
              child: DisclaimerAcceptanceHomeScreen(
                userName: user.displayName,
              ),
            );
          } else {
            return Scaffold(
              body: Center(
                child: PlatformCircularProgressIndicator(),
              ),
            );
          }
        });
  }
}

This works perfectly to get the user data and show the relevant screen.这非常适合获取用户数据并显示相关屏幕。 The only problem is, I don't know how to add the user's subscription status to this, to ensure only a user with an active subscription will be directed to the app's home page.唯一的问题是,我不知道如何将用户的订阅状态添加到此,以确保只有具有有效订阅的用户才会被定向到应用程序的主页。 The subscription status custom claim is returned as a future.订阅状态自定义声明作为未来返回。 In theory I would want to use something like this:理论上我想使用这样的东西:

  final idTokenResult =
      await FirebaseAuth.instance.currentUser?.getIdTokenResult(true);

and then:然后:

idTokenResult?.claims!['status']

The ideal condition that would return a user to the login screen would be:将用户返回到登录屏幕的理想情况是:

user == null || user.emailVerified == false || idTokenResult?.claims!['status'] != 'active'

This does work inside an async/await function but you'll see that my landing page is a stateless widget and is not asynchronous.这确实在 async/await function 中起作用,但您会看到我的登录页面是一个无状态小部件并且不是异步的。

How can I modify the landing page code, to allow me to get the Future 'status' custom claim value?我如何修改着陆页代码,以允许我获得未来的“状态”自定义声明值? I would appreciate any suggestions on this.我将不胜感激对此的任何建议。 Thank you!谢谢!

Did you consider using a FutureBuilder around the call to getIdTokenResult ?您是否考虑过在调用getIdTokenResult时使用FutureBuilder

Alternatively you can use a StreamBuilder on FirebaseAuth.instance.idTokenChanges() to get notified of all updates to the ID token.或者,您可以在FirebaseAuth.instance.idTokenChanges()上使用StreamBuilder来获取 ID 令牌所有更新的通知。

Based on Frank's comment, I modified my StreamBuilder to include FutureBuilder , where the future was the getIdTokenResult(true) function. This is what the above code looks like, modified as described:根据 Frank 的评论,我修改了我的StreamBuilder以包含FutureBuilder ,其中 future 是getIdTokenResult(true) function。这就是上面的代码,按照描述进行修改:

class LandingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthBase>(context, listen: false);
    return StreamBuilder<User?>(
        stream: auth.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            User? user = snapshot.data;
            user?.reload();
            user = snapshot.data;

            return FutureBuilder<IdTokenResult>(
              future: user?.getIdTokenResult(true),
              builder: (
                BuildContext context,
                AsyncSnapshot<IdTokenResult> snapshotData,
              ) {
                if (user == null ||
                    user.emailVerified == false ||
                    snapshotData.data?.claims!['status'] != 'active') {
                  return SignInHomePage.create(context);
                } else {
                  return Provider<User?>.value(
                    value: user,
                    child: DisclaimerAcceptanceHomeScreen(
                      userName: user.displayName,
                    ),
                  );
                }
              },
            );
          } else {
            return Scaffold(
              body: Center(
                child: PlatformCircularProgressIndicator(),
              ),
            );
          }
        });
  }
}

This now allows me to check the user's subscription status before letting them have access to the app.现在,这允许我在让用户访问该应用程序之前检查用户的订阅状态。

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

相关问题 如何使用 StreamBuilder 在 Flutter 中观察 Firebase 的变化 - How to observe Firebase changes in Flutter using StreamBuilder Flutter &amp; Firebase streamBuilder 分页 - Flutter & Firebase streamBuilder paginantion 如何在 Flutter 中将 Firebase 实时数据库读取为“字符串”(没有 Widget,streambuilder)? - How to read Firebase realtime database as "string"(without Widget, streambuilder) in Flutter? 在Flutter中使用带有FireBase数据的StreamBuilder时,如何将ListView替换为GroupedListView? - How to replace ListView with GroupedListView while using StreamBuilder with FireBase data in Flutter? 如何在 flutter 中使用 Streambuilder - How to use Streambuilder in flutter Flutter Firebase StreamBuilder如何只使用一个特定文件 - Flutter Firebase StreamBuilder how to use only one specific document Flutter &amp; Firebase:使用 StreamBuilder 减少读取次数 - Flutter & Firebase: reduce the number of reads with StreamBuilder Flutter - GridView 和带有 Firebase 实时数据库的 StreamBuilder - Flutter - GridView & StreamBuilder with Firebase Realtime DB Flutter Firebase 查询 Firestore 和 Streambuilder() 的问题 - Flutter Firebase Problems with Query Firestore and Streambuilder() Flutter Firebase 多文档 ID StreamBuilder - Flutter Firebase Multiple Document Id StreamBuilder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM