Flutter中的守卫 [英] Route Guards in Flutter

查看:107
本文介绍了Flutter中的守卫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular中,可以使用 canActivate 进行路线防护。

In Angular, one can use the canActivate for route guarding.

在Flutter中,如何去做关于它?守卫在哪里?您如何保护路线?

In Flutter, how would one go about it? Where is the guard placed? How do you guard routes?

我在考虑以下方面:


  • 用户登录。他们的令牌存储在共享首选项(正确的令牌存储方式?)中。

  • 用户关闭了应用程序。

  • 用户再次打开应用。在应用程序启动时,它将确定用户是否已登录(也许是一种检查令牌存储的服务),然后

  • 如果已登录,则加载主页路由

  • 如果未登录,请加载登录页面

  • User logged in. Their token is stored in Shared Preference (the right way to store tokens? )
  • User closed the app.
  • User opens app again. As the application starts, it determines if user is logged in (perhaps a service that checks the storage for token), and then
  • If logged in, load the homepage route
  • If not logged in, load the login page

推荐答案

也为这个问题而苦恼,最终为此使用了 FutureBuilder 。看一下我的路线:

I was stumbling over this problem too and ended up using a FutureBuilder for this. Have a look at my routes:

final routes = {
  '/': (BuildContext context) => FutureBuilder<AuthState>(
    // This is my async call to sharedPrefs
    future: AuthProvider.of(context).authState$.skipWhile((_) => _ == null).first,
    builder: (BuildContext context, AsyncSnapshot<AuthState> snapshot) {
      switch(snapshot.connectionState) {
        case ConnectionState.done:
          // When the future is done I show either the LoginScreen 
          // or the requested Screen depending on AuthState
          return snapshot.data == AuthState.SIGNED_IN ? JobsScreen() : LoginScreen()
        default:
          // I return an empty Container as long as the Future is not resolved
          return Container();
      }
    },
  ),
};

如果要在多条路径中重复使用代码,则可以扩展FutureBuilder。

If you want to reuse the code across multiple routes you could extend the FutureBuilder.

这篇关于Flutter中的守卫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆