go_router
Navigator แบบ built-in ของ Flutter เป็น imperative และไม่มีแนวคิดของ URL path หรือ nested route สำหรับทุกอย่างที่เกินกว่า simple push/pop flow — deep links, URL params, nested navigation, web URLs — คุณต้องใช้แพ็กเกจ go_router อย่างเป็นทางการ go_router ให้ declarative route configuration ที่ตรงกับ createBrowserRouter ของ React Router v6 เกือบทุกประการ
go_router ดูแลโดย Flutter team และเป็น routing solution ที่แนะนำอย่างเป็นทางการสำหรับแอป Flutter ใน production
หมายเหตุ:
go_routerต้องเพิ่มลงในpubspec.yamlของคุณ ไม่สามารถรันใน DartPad ได้ ดังนั้น code ในบทเรียนนี้มีไว้สำหรับอ้างอิงเท่านั้น
การเปรียบเทียบแบบ side-by-side
หัวข้อที่มีชื่อว่า “การเปรียบเทียบแบบ side-by-side”// React Router v6import { createBrowserRouter, RouterProvider, useParams } from 'react-router-dom';
const router = createBrowserRouter([ { path: '/', element: <RootLayout />, children: [ { index: true, element: <HomeScreen /> }, { path: 'products', element: <ProductList /> }, { path: 'products/:id', element: <ProductDetail /> }, ], },]);
// In ProductDetail:const { id } = useParams();// go_routerimport 'package:go_router/go_router.dart';
final router = GoRouter( routes: [ ShellRoute( builder: (context, state, child) => RootLayout(child: child), routes: [ GoRoute( path: '/', builder: (context, state) => const HomeScreen(), ), GoRoute( path: '/products', builder: (context, state) => const ProductList(), ), GoRoute( path: '/products/:id', builder: (context, state) { final id = state.pathParameters['id']!; return ProductDetail(id: id); }, ), ], ), ],);
// Navigate:context.go('/products/42');