تكرار السؤال: …
الإجابة المختصرة
تعرّف go_router شجرة مسارات بعناوين URL، وتحوّل الرابط إلى مكدس شاشات، وتتيح redirect مركزيًا يقرر إلى أين يذهب المستخدم بحسب حالة الدخول، مع دعم الروابط العميقة والويب.
الشرح
يُمرَّر الـ GoRouter إلى MaterialApp.router. تُعرَّف المسارات المتداخلة بمعاملات (مثل product/:id)، وتقرأ الشاشة المعاملات من state.pathParameters. تُنفَّذ دالة redirect قبل بناء المسار، وتعيد المسار البديل أو null لعدم التحويل، ويستخدم refreshListenable لإعادة التقييم عند تغيّر حالة الدخول. استخدم context.go لاستبدال المكدس وفق الرابط، و context.push لوضع شاشة فوق الحالية. احرص على ألا تُنتج قواعد redirect حلقة لا نهائية.
مثال بالكود
final router = GoRouter(
initialLocation: '/',
refreshListenable: authState, // re-run redirect when the auth state changes
redirect: (context, state) {
final loggedIn = authState.isLoggedIn;
final onLogin = state.matchedLocation == '/login';
if (!loggedIn && !onLogin) return '/login';
if (loggedIn && onLogin) return '/';
return null; // no redirect
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: 'product/:id',
builder: (context, state) => ProductPage(id: state.pathParameters['id']!),
),
],
),
GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
],
);
// MaterialApp.router(routerConfig: router);
// context.go('/product/42'); // rebuilds the stack for this URL
// context.push('/product/42'); // pushes on top of the current stackأخطاء شائعة
- كتابة منطق redirect يعيد توجيه المستخدم إلى مسار يعيده بدوره إلى المسار الأول فتنشأ حلقة لا نهائية.
- استخدام context.go عندما يُراد الرجوع إلى الشاشة السابقة، فيُستبدل المكدس ويضيع زر الرجوع المتوقع.