Private and public routers in Flutter

戏子无情 提交于 2021-02-11 12:50:57

问题


I am new in Flutter and my task is to divide path into public and private. For solution, this I used the suggested advice from Dima Rostopira answered Jul 28 '20 at 8:29 in this topic

My main problem is that instead of the shown in the example:

MyAuth.isUserLoggedIn

I need to use an asynchronous function:

Auth().isAuth()

but example solution does not work with an asynchronous function.

Can someone help solve this problem?

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 example, how routers called in main.dart

MaterialApp(
       title: 'Main App',
       routes: NavigationRoutes().routes
  ),

来源:https://stackoverflow.com/questions/66012904/private-and-public-routers-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!