在Angular中,可以使用canActivate进行路线防护。
在Flutter中,该如何处理?守卫在哪里?您如何守护路线?
我在考虑以下方面:
Mas*_*lch 11
我也遇到了这个问题,最终FutureBuilder为此使用了 a 。看看我的路线:
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();
}
},
),
};
Run Code Online (Sandbox Code Playgroud)
如果您想跨多个路由重用代码,您可以扩展 FutureBuilder。
我认为本身没有路由保护机制,但是您可以在main加载应用程序之前在函数中执行逻辑,或者onGenerateRoute使用MaterialApp. 在您的情况下,一种方法是等待一个异步函数,该函数在加载初始路由之前检查用户是否已登录。就像是
main() {
fetchUser().then((user) {
if (user != null) runApp(MyApp(page: 'home'));
else runApp(MyApp(page: 'login'));
});
}
Run Code Online (Sandbox Code Playgroud)
但您可能也对 Shrine 应用程序的实现方式感兴趣。在任何情况下,他们都将登录页面作为初始路由,并在用户登录时将其删除。这样用户就会看到登录页面,直到确定他们是否登录为止。我在下面包含了相关片段。
class ShrineApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shrine',
home: HomePage(),
initialRoute: '/login',
onGenerateRoute: _getRoute,
);
}
Route<dynamic> _getRoute(RouteSettings settings) {
if (settings.name != '/login') {
return null;
}
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => LoginPage(),
fullscreenDialog: true,
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不想让他们在登录后看到登录页面,请使用第一种方法,您可以通过探索此答案runApp来控制在具有 UI之前显示的启动屏幕。
| 归档时间: |
|
| 查看次数: |
2170 次 |
| 最近记录: |