Search code examples
flutterdartroutesprovider

passing Auth data with go_router


In my project, I implement the Provider method to manage state, and I'd like to share auth provider info with the go router package to keep users logged in

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (ctx) => Auth(),
          ),
         ListenableProxyProvider<Auth, AppRouter>(
            update: (_, authObj, prevOrders) =>
               AppRouter(authObj)
          ),
}

and within my AppRouter class I have a constructer to get auth data :

class AppRouter with ChangeNotifier {
  final Auth authData;
  AppRouter(this.authData);
  final router = GoRouter(
    initialLocation: '/',
    routes: [

     
      GoRoute(
        name: root,
        path: '/',
        builder: (context, state) => TabsScreen(),
        // redirect: (state) => state.namedLocation(authScreen),
      ),
      GoRoute(
        name: mainScreen,
        path: '/main-screen',
        builder: (context, state) => HomeScreen(),
      ),
      GoRoute(
        name: authscreen,
        path: '/auth-screen',
        builder: (context, state) => AuthScreen(),
      ),

],

    redirect: (state) {
      final loginLoc = state.namedLocation(authScreen);
      final loggingIn = state.subloc == loginLoc;

  var loggedIn = authData.isLoggedIn;
 if (!loggedIn && !loggingIn) return loginLoc;
  if (loggedIn && (loggingIn)) return root;

      return null;
    },

however I can't access authData within my class and I get this error :

The instance member 'authData' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression

Solution

  • this article helped me solve my problem and Also there is complete guide about implementing Navigation 2.0 using Go_Router :

    Flutter Navigator 2.0: Using go_router