Milad-Akarie / auto_route_library

Flutter route generator
MIT License
1.59k stars 405 forks source link

Issues Implementing Custom rebuildAll and popAllAndPushAll Methods in auto_route #1964

Open guplem opened 6 months ago

guplem commented 6 months ago

Issue Description:

I am experiencing issues creating custom methods to rebuildAll and popAllAndPushAll methods for the auto_route package.

Details:

The rebuildAll method collects all route data from the stack and converts them into PageRouteInfo objects. It then calls popAllAndPushAll if the list of route information is not empty.

The popAllAndPushAll method attempts to pop all routes and push new ones, but both options I've tried to do not work:

  1. Using pushAndPopUntil does not complete the future.
  2. Using popForced in a loop does not pop the root route and results in route duplication in the stack after pushAll.

They are both implemented inside my class AuthGuard that extends AutoRouteGuard.

Here are the implementations:

Future<void> rebuildAll() async {
  List<RouteData> routesDataList = stack.map((e) => e.routeData).toList();
  List<PageRouteInfo<dynamic>> routeInfos = routesDataList.map((routeData) => PageRouteInfo.fromMatch(routeData.topMatch)).toList();

  if (routeInfos.isNotEmpty) {
    await popAllAndPushAll(routeInfos);
  }
}

Future<void> popAllAndPushAll(List<PageRouteInfo<dynamic>> routeInfos) async {
  List<RouteData> routesInStack = stack.map((e) => e.routeData).toList();
  print("Popping all routes (${routesInStack.map((e) => e.name).join(", ")}) and pushing ${routeInfos.map((e) => e.routeName).join(", ")}");

  // OPTION A: This does not work
  await pushAndPopUntil(routeInfos.first, predicate: (_) => false); // This never finishes the future
  if (routeInfos.length > 1) await pushAll(routeInfos.skip(1).toList());

  // OPTION B: This does not work either
  // for(int i = 0; i < routesInStack.length; i++) {
  //   popForced(); // This does not seem to pop the root route, it is duplicated in the stack after the pushAll
  // }
  // await pushAll(routeInfos);

  print("Result of popAllAndPushAll: ${stack.map((e) => e.routeData.name).join(", ")}");
}

Questions:

  1. How can I properly implement popAllAndPushAll to ensure all routes are popped and the new ones are pushed correctly?
  2. Is there a recommended approach for achieving the intended functionality using auto_route?
  3. Could there be an issue with pushAndPopUntil or popForced that I am not aware of?

Environment:

Expected Behavior:

All routes should be popped, and the new routes should be pushed as specified in the routeInfos list.

Actual Behavior:

The methods do not work as intended:

guplem commented 6 months ago

In case more code is relevant to understand the issue, here you have my raw AppRouter:

It contains custom functions and stuff such as Debug.log which are "prints".

import 'dart:convert';

import 'package:auto_route/auto_route.dart';
import 'package:bondy/V2/modules/analytics/analytics_service.dart';
import 'package:bondy/V2/modules/chat_v3/service.dart';
import 'package:bondy/V2/modules/global/global_data_service.dart';
import 'package:bondy/V2/modules/maintenance/service.dart';
import 'package:bondy/V2/modules/router/guards/auth_guard.dart';
import 'package:bondy/V2/modules/router/guards/debug_guard.dart';
import 'package:bondy/V2/modules/router/guards/pre_login_guard.dart';
import 'package:bondy/V2/modules/router/router.gr.dart';
import 'package:bondy/V2/modules/update/service.dart';
import 'package:bondy/V2/utils/library.dart';
import 'package:flutter/widgets.dart';

@AutoRouterConfig(replaceInRouteName: 'Page,Route') //"HomePage" will be generated as "HomeRoute" because of the replaceInRouteName property
class AppRouter extends $AppRouter implements AutoRouteGuard {
  BuildContext? get context => super.navigatorKey.currentContext;

  static final AppRouter _instance = AppRouter.internal(GlobalKey<NavigatorState>());

  AppRouter.internal(GlobalKey<NavigatorState> navigatorKey) : super(navigatorKey: navigatorKey);

  factory AppRouter() => _instance;

  @override
  List<AutoRoute> get routes => [
        AutoRoute(page: HomeRoute.page, path: "/", guards: [PreLoginGuard(), AuthGuard()]),
        AutoRoute(page: ForceUpdateRoute.page, path: "/update"),
        AutoRoute(page: MaintenanceRoute.page, path: "/maintenance"),
        AutoRoute(page: AuthRoute.page, path: "/auth"),

        AutoRoute(page: ProfileRoute.page, path: "/profile/:userId", guards: [AuthGuard()]),
        AutoRoute(page: PeopleRoute.page, path: "/people", guards: [AuthGuard()]),
        AutoRoute(page: LiveRoute.page, path: "/lives", guards: [AuthGuard()]),
        AutoRoute(page: PlanRoute.page, path: "/plan/:planId", guards: [AuthGuard()]),
        AutoRoute(page: SettingsRoute.page, path: "/settings", guards: [AuthGuard()]),
        AutoRoute(page: DevToolsV2Route.page, path: "/dev-tools", guards: [DebugGuard()]),
        AutoRoute(page: EmptyRoute.page, path: "/empty"),
        AutoRoute(page: WebViewRoute.page, path: "/web-view", guards: [AuthGuard()]),
        AutoRoute(page: MapRoute.page, path: "/map"),
        AutoRoute(page: ChatV3ListsRoute.page, path: "/chats", guards: [AuthGuard()]),
        AutoRoute(page: ChatV3Route.page, path: "/chat/:cid", guards: [AuthGuard()]),
        AutoRoute(page: PreLoginRoute.page, path: "/pre-login"),
        AutoRoute(page: LogoutRoute.page, path: "/logout"),
        RedirectRoute(redirectTo: '/', path: "*"), // https://github.com/Milad-Akarie/auto_route_library#wildcards
      ];

  @override
  void onNavigation(NavigationResolver resolver, StackRouter router) {
    if (resolver.route.name == ForceUpdateRoute.name || resolver.route.name == MaintenanceRoute.name) {
      resolver.next();
    } else {
      if (MaintenanceService().isMaintenance) {
        resolver.redirect(const MaintenanceRoute(), replace: true);
      } else if (!UpdateService().isVersionValid) {
        resolver.redirect(const ForceUpdateRoute(), replace: true);
      } else {
        resolver.next();
      }
    }
  }

  static Uri planDeepLink(String planId) {
    return Uri(
      scheme: GlobalDataService.webUrl.scheme,
      host: GlobalDataService.webUrl.host,
      path: "/plan/$planId",
    );
  }

  removeAllPlanRoutesOf({required String planId}) {
    removeWhere((route) {
      return route.name == PlanRoute.name && (route.args as PlanRouteArgs).planId == planId;
    });
  }

  removeAllChatRoutesOf({String? chatCid, String? planId}) {
    Debug.logAssertion("removeAllChatRoutesOf: chatId and planId cannot be null at the same time", showIf: chatCid == null && planId == null);

    chatCid ??= "${ChatType.plan.value}:${planId!}";

    removeWhere((route) {
      if (route.name == ChatV3Route.name) {
        final ChatV3RouteArgs args = route.args as ChatV3RouteArgs;
        return (args.cid == chatCid) || (args.channel?.cid == chatCid);
      }

      return false;
    });
  }

  Future<void> rebuildAll() async {
    List<RouteData> routesDataList = stack.map((e) => e.routeData).toList();
    List<PageRouteInfo<dynamic>> routeInfos = routesDataList.map((routeData) => PageRouteInfo.fromMatch(routeData.topMatch)).toList();

    if (routeInfos.isNotEmpty) {
      await popAllAndPushAll(routeInfos);
    }
  }

  Future<void> popAllAndPushAll(List<PageRouteInfo<dynamic>> routeInfos) async {
    List<RouteData> routesInStack = stack.map((e) => e.routeData).toList();
    Debug.logAssertion("No routes to pop", showIf: routesInStack.isEmpty);
    Debug.log("Popping all routes (${routesInStack.map((e) => e.name).join(", ")}) and pushing ${routeInfos.map((e) => e.routeName).join(", ")}");

    // OPTION A: This does not work
    await pushAndPopUntil(routeInfos.first, predicate: (_) => false); // This never finishes the future
    if (routeInfos.length > 1) await pushAll(routeInfos.skip(1).toList());

    // OPTION B: This does not work either
    // for(int i = 0; i < routesInStack.length; i++) {
    //   popForced(); // This does not seem to pop the root route, it is duplicated in the stack after the pushAll
    // }
    // await pushAll(routeInfos);

    Debug.log("Result of popAllAndPushAll: ${stack.map((e) => e.routeData.name).join(", ")}");
  }
}
guplem commented 6 months ago

More information that might be relevant:

I do have the AuthGuard that looks like this:

class AuthGuard extends AutoRouteGuard {
  @override
  void onNavigation(NavigationResolver resolver, StackRouter router) {

    bool userIsLogged = AuthServiceV2().isLoggedIn;

    if (userIsLogged) {
      resolver.next(true);
    } else {
      resolver.redirect(const AuthRoute());
      AuthServiceV2().loginResultCallback = (bool didLogin) async => resolver.next(didLogin);
    }
  }
}

And then in my setUserId (which is my equivalent to "login/logout" handling, I do the following:

  Future<void> setUserId(String? newUser) async {
    _userId = newUser;

    if (newUser != null) {
      await loginResultCallback?.call(true);
      loginResultCallback = null;

      // Recreate all routes, Expect to have "redirected route" by the AuthGuard to be already replaced by the loginResultCallback. All the stack should be rebuilt (including the root)
      await AppRouter().rebuildAll();
    } else {
      // Reroute, Expected to have the full stack rebuilt (including root) and setting "HomeRoute" as the root.
      if (AppRouter().stack.isNotEmpty) await AppRouter().popAllAndPushAll([const HomeRoute()]);
    }
  }
guplem commented 6 months ago

My SOLUTION

I've ended up with a solution which, even though it is not 100% ideal, it gets you 90% of the way (I am only missing that I don't feel completely safe using it).

I removed the "futures" from the equation and since I detected that I can not reliably await for them, and added Post Frame Callbacks to execute the stuff that should be executed afterwards.

These are my final methods to rebuildAll and popAllAndPushAll:

  void rebuildAll() {
    List<RouteData> routesDataList = stack.map((e) => e.routeData).toList();
    List<PageRouteInfo<dynamic>> routeInfos = routesDataList.map((routeData) => PageRouteInfo.fromMatch(routeData.topMatch)).toList();

    if (routeInfos.isNotEmpty) {
      popAllAndPushAll(routeInfos);
    }
  }

  void popAllAndPushAll(List<PageRouteInfo<dynamic>> routeInfos) {
    List<RouteData> routesInStack = stack.map((e) => e.routeData).toList();

    /*await*/ pushAndPopUntil(routeInfos.first, predicate: (_) => false); // This never finishes the future. ISSUE: https://github.com/Milad-Akarie/auto_route_library/issues/1964
    if (routeInfos.length > 1) WidgetsBinding.instance.addPostFrameCallback((_) => pushAll(routeInfos.skip(1).toList()));
  }

And my AuthService now is managed like this:

  Future<void> setUserId(String? newUser) async {
    _userId = newUser;

    if (newUser != null) {
      await loginResultCallback?.call(true);
      loginResultCallback = null;

      WidgetsBinding.instance.addPostFrameCallback((_) async => AppRouter().rebuildAll());
    } else {
      if (AppRouter().stack.isNotEmpty) AppRouter().popAllAndPushAll([const HomeRoute()]);
    }
  }

This works, but it seems odd. At least, I believe there is an issue with the future of the pushAndPopUntil since if I await for it to finish, the next instruction is not executed.

SaurabhS78 commented 2 months ago

After multiple attempts and failures while trying to use the replaceAll with updateExistingRoutes: false approach, I was able to implement redirect and reload functionality in our application with two distinct approaches:

Approach 1: Reload Entire App

For a complete application reload, I utilized the Phoenix.rebirth() method from the flutter_phoenix package. This method effectively restarts the entire application, providing a clean state immediately after redirection.

void performRedirectAndRebirth(BuildContext context) {
  // Perform the navigation
  context.router.replaceAll([YourNewPageRoute()]);

  // After navigation, restart the entire application
  Phoenix.rebirth(context);
}

Approach 2: Invalidate State Using Riverpod

In scenarios where a full app reload isn't necessary, I used Riverpod's ref.invalidate function to selectively invalidate the state. This method is more granular and avoids the overhead of a complete app restart:

void performRedirectAndInvalidateState(WidgetRef ref, BuildContext context) {
  // Perform the navigation
  context.router.replace(YourNewPageRoute());

  // Invalidate a specific provider to refresh its consumers
  ref.invalidate(someProvider);
}