Flutter中的守卫
问题内容:
在Angular中,可以使用canActivate
进行路线防护。
在Flutter中,该如何处理?守卫在哪里?您如何守护路线?
我在考虑以下方面:
- 用户登录。他们的令牌存储在“共享首选项”中(正确的令牌存储方式?)
- 用户关闭了该应用程序。
- 用户再次打开应用。在应用程序启动时,它确定用户是否已登录(也许是一种检查令牌存储的服务),然后
- 如果登录,则加载主页路由
- 如果未登录,请加载登录页面
问题答案:
我也在这个问题上绊脚石,最终FutureBuilder
为此使用了一个。看看我的路线:
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。