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(
title: 'Named Routes Demo',
initialRoute: '/home',
routes: {
'/home': (context) => const HomeScreen(),
'/details': (context) => const DetailsScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home Screen')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/details');
},
child: const Text('Go to Details'),
),
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details Screen')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/home');
},
child: const Text('Back to Home'),
),
),
);
}
}
This Flutter app uses named routes to navigate between two screens: HomeScreen and DetailsScreen.
In MaterialApp, we define the routes map with keys '/home' and '/details' pointing to their respective screen widgets.
The initialRoute is set to '/home' so the app starts on the HomeScreen.
On HomeScreen, pressing the button calls Navigator.pushNamed(context, '/details') to go to DetailsScreen.
On DetailsScreen, pressing the button calls Navigator.pushNamed(context, '/home') to go back to HomeScreen.
This approach keeps navigation organized and easy to manage, especially as apps grow larger.