ข้ามไปยังเนื้อหา

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 ในบทเรียนนี้มีไว้สำหรับอ้างอิงเท่านั้น

React
// React Router v6
import { 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();
Flutter
// go_router
import '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');
สิ่งที่เทียบเท่ากับ useParams() ของ React Router v6 ใน go_router คืออะไร?
ความแตกต่างระหว่าง context.go() และ context.push() ใน go_router คืออะไร?
ShellRoute ใน go_router ใช้ทำอะไร?
go_router แตกต่างจาก Flutter built-in named routes สำหรับ web app อย่างไร?