0

I have implemented go_router in my flutter app and trying to navigate to a screen using this implementation

() {
      context.goNamed(
      RouteNameConstants.profilecontent,
      pathParameters: {"clicked": "about"},
   );             

even though I am not getting any error but the navigation is not working, I click on button and nothing works, please help

this is what I am getting in console instead of successfully navigating

D/VRI[MainActivity](32580): handleWindowFocusChanged mWindowFocusChanged true mUpcomingWindowFocus false mAdded true
D/VRI[MainActivity](32580): onFocusEvent true
D/VRI[MainActivity](32580): send msg MSG_WINDOW_FOCUS_CHANGED with caller android.view.ViewRootImplExtImpl.markAndDumpWindowFocusChangeMsg:956 android.view.ViewRootImpl.windowFocusChanged:9837 android.view.ViewRootImpl$WindowInputEventReceiver.onFocusEvent:9550 android.os.MessageQueue.nativePollOnce:-2 android.os.MessageQueue.next:349 android.os.Looper.loopOnce:186 android.os.Looper.loop:351 android.app.ActivityThread.main:8404 java.lang.reflect.Method.invoke:-2 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run:584 com.android.internal.os.ZygoteInit.main:1013 <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack> <bottom of call stack>
D/VRI[MainActivity](32580): handleWindowFocusChanged mWindowFocusChanged true mUpcomingWindowFocus true mAdded true
D/TrafficStats(32580): tagSocket(3) with statsTag=0xffffffff, statsUid=-1
D/TrafficStats(32580): tagSocket(199) with statsTag=0xffffffff, statsUid=-1
D/OplusScrollToTopManager(32580): com.shoppier.discountlo/com.shoppier.discountlo.MainActivity,This DecorView@c3dec38[MainActivity] change focus to true

here are my routes defined

import 'package:discountlo/core/route_constant.dart';
import 'package:discountlo/features/auth/views/otp_view.dart';
import 'package:discountlo/features/auth/views/phone_view.dart';
import 'package:discountlo/features/home/view/filter_view.dart';
import 'package:discountlo/features/home/view/profile_content_view.dart';
import 'package:discountlo/features/home/view/profile_view.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:discountlo/features/auth/views/onboarding_screen.dart';
import 'package:discountlo/features/auth/views/splash_view.dart';
import 'package:discountlo/features/home/view/home_view.dart';
import 'auth_changes.dart';
import 'error_page.dart';
import 'package:flutter/material.dart';
import 'features/auth/controller/auth_controller.dart';

final _key = GlobalKey<NavigatorState>();

final routeProvider = Provider<GoRouter>(
  (ref) {
    return GoRouter(
      navigatorKey: _key,
      debugLogDiagnostics: true,
      routes: [
        GoRoute(
          name: RouteNameConstants.home,
          path: "/",
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: const HomeView(),
          ),
        ),
        GoRoute(
          path: "/splash",
          name: RouteNameConstants.splash,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: const SplashScreen(),
          ),
        ),
        GoRoute(
          path: "/otp",
          name: RouteNameConstants.otp,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: OTPView(
              phoneNumber: state.pathParameters['phoneNumber']!,
            ),
          ),
        ),
        GoRoute(
          path: "/phone",
          name: RouteNameConstants.phone,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: const PhoneView(),
          ),
        ),
        GoRoute(
          path: "/profile",
          name: RouteNameConstants.profile,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: const ProfileView(),
          ),
        ),
        GoRoute(
          path: "/profilecontent",
          name: RouteNameConstants.profilecontent,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: ProfileContentView(
              clicked: state.pathParameters['clicked']!,
            ),
          ),
        ),
        GoRoute(
          path: "/onboard",
          name: RouteNameConstants.onboarding,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: const OnboardingView(),
          ),
        ),
        GoRoute(
          path: "/error/:text",
          name: RouteNameConstants.error,
          pageBuilder: (BuildContext context, GoRouterState state) =>
              MaterialPage(
            child: ErrorPage(text: state.pathParameters['text']!),
          ),
        ),
        GoRoute(
          path: "/auth/:uid",
          name: RouteNameConstants.authState,
          pageBuilder: (BuildContext context, GoRouterState state) {
            return MaterialPage(
              child: AuthChanges(uid: state.pathParameters['uid']!),
            );
          },
        ),
        GoRoute(
          path: "/filter/:index/:category",
          name: RouteNameConstants.filter,
          pageBuilder: (BuildContext context, GoRouterState state) {
            debugPrint("sdvf ${state.pathParameters}");
            return MaterialPage(
              child: FilterView(
                index: double.tryParse(state.pathParameters['index']!)!.toInt(),
                category: state.pathParameters['category']!,
              ),
            );
          },
        ),
      ],
      redirect: (context, state) {
        final loginState = ref.watch(authStateChangeProvider);
        if (loginState.isLoading) {
          return state.namedLocation(RouteNameConstants.splash);
        } else if (loginState.hasError) {
          return state.namedLocation(
            RouteNameConstants.error,
            pathParameters: {
              "text": loginState.error.toString(),
            },
          );
        } else if (loginState.value != null) {
          return state.namedLocation(RouteNameConstants.authState,
              pathParameters: {"uid": loginState.value!.uid});
        } else {
          return state.namedLocation(RouteNameConstants.onboarding);
        }
      },
    );
  },
);

with these constant route names

class RouteNameConstants {
  static const String home = 'home';
  static const String splash = 'splash';
  static const String onboarding = 'onboard';
  static const String authState = 'auth';
  static const String error = 'error';
  static const String filter = 'filter';
  static const String profile = 'profile';
  static const String phone = 'phone';
  static const String otp = 'otp';
  static const String profilecontent = 'profilecontent';
}

with that main.dart

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) async {
    await Firebase.initializeApp();
    await FirebaseAppCheck.instance
        .activate(androidProvider: AndroidProvider.playIntegrity);

    runApp(
      const ProviderScope(
        child: MyApp(),
      ),
    );
  });
  FlutterError.demangleStackTrace = (StackTrace stack) {
    if (stack is stack_trace.Trace) return stack.vmTrace;
    if (stack is stack_trace.Chain) return stack.toTrace().vmTrace;
    return stack;
  };
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      title: 'DiscountLo',
      theme: AppTheme.theme,
      locale: ref.watch(languageNotifierProvider),
      localizationsDelegates: {
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate
      },
      supportedLocales: [Locale("en"), Locale("hi")],
      routerDelegate: ref.watch(routeProvider).routerDelegate,
      routeInformationParser: ref.watch(routeProvider).routeInformationParser,
      routeInformationProvider: ref.watch(routeProvider).routeInformationProvider,
    );
  }
}
abhi jain
  • 41
  • 1
  • 5
  • I'd start with adding a print statement to the button's onTap method to make sure you're actually running the code you think you are. Maybe run in debugger and set some break points. – John Weidner Aug 05 '23 at 10:52
  • Function is getting called I tried adding debugPrint – abhi jain Aug 05 '23 at 11:03
  • I tried running it on debugger and I found this bug [GoRouter] getting location for name: "phone" [GoRouter] going to /phone [GoRouter] getting location for name: "onboard" [GoRouter] redirecting to RouteMatchList(/onboard) [GoRouter] getting location for name: "onboard" – abhi jain Aug 05 '23 at 11:09
  • sorry found the bug, I should return null at redirect when my loginState value is null to be able to navigate to any screen return state.namedLocation(RouteNameConstants.onboarding); – abhi jain Aug 05 '23 at 11:15

0 Answers0