我是 Flutter 新手,我的任务是将路径分为公共路径和私有路径。对于解决方案,我使用了 Dima Rostopira 的建议建议,于 20 年 7 月 28 日 8:29 在此topic
我的主要问题是,而不是 example 中显示的:
<块引用>MyAuth.isUserLoggedIn
我需要使用异步函数:
<块引用>Auth().isAuth()
但 example 解决方案不适用于异步函数。
有人可以帮忙解决这个问题吗?
ConditionalRouter.dart
class ConditionalRouter extends MapMixin<String, WidgetBuilder> {
final Map<String, WidgetBuilder> public;
final Map<String, WidgetBuilder> private;
ConditionalRouter({this.public, this.private});
@override
WidgetBuilder operator [](Object key) {
if (public.containsKey(key)) return public[key];
if (private.containsKey(key)) {
if (Auth().isAuth()) { //PROBLEM IS HERE, BECAUSE Auth().isAuth() IS ASYNC
return private[key];
}
return (context) => AuthScreen();
}
return null;
}
@override
void operator []=(key, value) {}
@override
void clear() {}
@override
Iterable<String> get keys {
final set = Set<String>();
set.addAll(public.keys);
set.addAll(private.keys);
return set;
}
@override
WidgetBuilder remove(Object key) {
return public[key] ?? private[key];
}
}
NavigationRoutes.dart
class NavigationRoutes {
static const agreementsScreen = "/agreementsScreen";
static const documentsScreen = "/documentsScreen";
var routes = ConditionalRouter(
public: {
DocumentsScreen.routeName: (context) => DocumentsScreen()
},
private: {
AgreementsScreen.routeName: (context) => AgreementsScreen(),
});
}
Auth.dart
Future<bool> isAuth() async {
print('Checking AUTH with isAuth()');
bool isAlreadyLogin = false;
/*
...
asynchronous logic, that check is user authenticated or active session or not
...
*/
return isAlreadyLogin;
}
main.dart 例如,路由器如何在 main.dart 中调用
MaterialApp(
title: 'Main App',
routes: NavigationRoutes().routes
),