惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
爱范儿
爱范儿
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
IT之家
IT之家
有赞技术团队
有赞技术团队
美团技术团队
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Engineering at Meta
Engineering at Meta
T
Tailwind CSS Blog
J
Java Code Geeks
Martin Fowler
Martin Fowler
I
InfoQ
小众软件
小众软件
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Flutter GoRouter Complete Guide — Full Control Over Navig...
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Flutter GoRouter Complete Guide — Full Control Over Navigation 2.0

GoRouter is Flutter's officially recommended routing package. URL-based navigation, deep links, auth guards, and nested routes — all with clean, readable code.

Basic Setup

dependencies:
  go_router: ^13.0.0

Enter fullscreen mode Exit fullscreen mode

final router = GoRouter(
  initialLocation: '/',
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
    ),
    GoRoute(
      path: '/profile/:userId',
      builder: (context, state) {
        final userId = state.pathParameters['userId']!;
        return ProfilePage(userId: userId);
      },
    ),
    GoRoute(
      path: '/settings',
      builder: (context, state) => const SettingsPage(),
    ),
  ],
);

void main() {
  runApp(MaterialApp.router(routerConfig: router));
}

Enter fullscreen mode Exit fullscreen mode

Navigation

// Push (keeps back stack)
context.push('/settings');

// Go (replaces history)
context.go('/home');

// With path parameters
context.push('/profile/user-123');

// With query parameters
context.push('/search?q=flutter&tag=dart');

// Go back
context.pop();

// Await a result
final confirmed = await context.push<bool>('/confirm');
if (confirmed == true) proceed();

Enter fullscreen mode Exit fullscreen mode

Auth Guard

final router = GoRouter(
  refreshListenable: authNotifier,
  redirect: (context, state) {
    final isAuthenticated = authNotifier.isAuthenticated;
    final isGoingToLogin = state.matchedLocation == '/login';

    if (!isAuthenticated && !isGoingToLogin) {
      return '/login?redirect=${state.uri}';
    }
    if (isAuthenticated && isGoingToLogin) {
      return '/';
    }
    return null;
  },
  routes: [
    GoRoute(path: '/login', builder: (_, __) => const LoginPage()),
    GoRoute(path: '/', builder: (_, __) => const HomePage()),
    GoRoute(path: '/profile', builder: (_, __) => const ProfilePage()),
  ],
);

Enter fullscreen mode Exit fullscreen mode

Nested Routes with ShellRoute

// Keep bottom nav bar while switching tabs
final router = GoRouter(
  routes: [
    ShellRoute(
      builder: (context, state, child) => ScaffoldWithNavBar(child: child),
      routes: [
        GoRoute(path: '/home', builder: (_, __) => const HomePage()),
        GoRoute(path: '/search', builder: (_, __) => const SearchPage()),
        GoRoute(
          path: '/profile',
          builder: (_, __) => const ProfilePage(),
          routes: [
            GoRoute(path: 'edit', builder: (_, __) => const EditProfilePage()),
          ],
        ),
      ],
    ),
  ],
);

class ScaffoldWithNavBar extends StatelessWidget {
  final Widget child;
  const ScaffoldWithNavBar({required this.child, super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: child,
      bottomNavigationBar: NavigationBar(
        selectedIndex: _selectedIndex(context),
        onDestinationSelected: (i) => _navigate(i, context),
        destinations: const [
          NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
          NavigationDestination(icon: Icon(Icons.search), label: 'Search'),
          NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
        ],
      ),
    );
  }

  int _selectedIndex(BuildContext context) {
    final loc = GoRouterState.of(context).uri.toString();
    if (loc.startsWith('/search')) return 1;
    if (loc.startsWith('/profile')) return 2;
    return 0;
  }

  void _navigate(int index, BuildContext context) {
    switch (index) {
      case 0: context.go('/home');
      case 1: context.go('/search');
      case 2: context.go('/profile');
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Riverpod Integration

@riverpod
GoRouter router(Ref ref) {
  final authState = ref.watch(authStateProvider);

  return GoRouter(
    refreshListenable: _AuthNotifier(ref),
    redirect: (context, state) {
      final isLoggedIn = authState.valueOrNull != null;
      final isLoginRoute = state.matchedLocation == '/login';

      if (!isLoggedIn && !isLoginRoute) return '/login';
      if (isLoggedIn && isLoginRoute) return '/';
      return null;
    },
    routes: routes,
  );
}

@override
Widget build(BuildContext context, WidgetRef ref) {
  return MaterialApp.router(routerConfig: ref.watch(routerProvider));
}

Enter fullscreen mode Exit fullscreen mode

Deep Links and Custom Transitions

// GoRouter resolves URL → route automatically
// https://myapp.com/profile/user-123 → ProfilePage(userId: 'user-123')

// Custom page transition
GoRoute(
  path: '/details/:id',
  pageBuilder: (context, state) => CustomTransitionPage(
    key: state.pageKey,
    child: DetailsPage(id: state.pathParameters['id']!),
    transitionsBuilder: (context, animation, _, child) =>
        FadeTransition(opacity: animation, child: child),
  ),
),

Enter fullscreen mode Exit fullscreen mode

Summary

GoRouter delivers:

  • URL-based navigation with automatic deep link support
  • Auth guards that auto-redirect unauthenticated users
  • ShellRoute for persistent bottom nav during tab switches
  • Riverpod integration for reactive routing on state changes

For any Flutter app of medium complexity or above, GoRouter is the routing solution to reach for first.


Building an AI Life Management app with Flutter × Supabase at 自分株式会社. Sharing indie dev insights every week.