Named Routes (เส้นทางที่ตั้งชื่อ)
ใน React Router คุณกำหนด route configuration — array หรือ JSX tree ของ <Route path="..." element={...} /> objects — และ router จะ render component ที่ตรงกันตาม URL ปัจจุบัน Flutter มีสิ่งที่เทียบเคียงได้แบบ built-in ที่เรียบง่ายกว่า: routes map บน MaterialApp ที่เชื่อมโยง string name กับ builder function การเรียก Navigator.pushNamed(context, '/detail') จะค้นหาชื่อใน map และ push หน้าจอที่ตรงกัน
Named routes แก้ปัญหาเดียวกับ path config ของ React Router: คุณแยก navigation call site ออกจาก screen widget จริง ๆ ทำให้สามารถเปลี่ยนชื่อหรือย้าย screen ได้โดยไม่ต้องอัปเดตทุก push call
การเปรียบเทียบแบบ side-by-side
หัวข้อที่มีชื่อว่า “การเปรียบเทียบแบบ side-by-side”// React Router v6 — route configimport { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([ { path: '/', element: <HomeScreen /> }, { path: '/detail', element: <DetailScreen /> }, { path: '/profile', element: <ProfileScreen /> },]);
// Navigate by path stringnavigate('/detail');navigate('/profile');// Flutter — named routes mapMaterialApp( initialRoute: '/', routes: { '/': (context) => const HomeScreen(), '/detail': (context) => const DetailScreen(), '/profile': (context) => const ProfileScreen(), },);
// Navigate by nameNavigator.pushNamed(context, '/detail');Navigator.pushNamed(context, '/profile');ตัวอย่างที่รันได้
หัวข้อที่มีชื่อว่า “ตัวอย่างที่รันได้”import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomeScreen(),
'/about': (context) => const AboutScreen(),
'/contact': (context) => const ContactScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/about'),
child: const Text('About'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/contact'),
child: const Text('Contact'),
),
],
),
),
);
}
}
class AboutScreen extends StatelessWidget {
const AboutScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('About')),
body: const Center(child: Text('About page')),
);
}
}
class ContactScreen extends StatelessWidget {
const ContactScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Contact')),
body: const Center(child: Text('Contact page')),
);
}
}