How to Add Navigation and Routing in Flutter Apps
Navigation is a core part of any mobile application, enabling users to move between different screens or pages. In Flutter, navigation and routing are handled efficiently through built-in tools and widgets. Whether you're building a simple app or a complex one with multiple screens, understanding how to implement navigation is essential. This blog covers the basics of adding navigation and routing in Flutter.
What is Routing in Flutter?
Routing is the process of moving from one screen (called a "route") to another in a Flutter app. Each route is typically a widget, and Flutter manages routes using the Navigator widget.
Basic Navigation Using Navigator.push
To navigate from one screen to another, you can use:
dart
Copy
Edit
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
This code pushes a new route onto the stack, displaying the SecondScreen widget.
To go back:
dart
Copy
Edit
Navigator.pop(context);
Example: Two-Screen App
dart
Copy
Edit
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: FirstScreen()));
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("First Screen")),
body: Center(
child: ElevatedButton(
child: Text("Go to Second Screen"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Second Screen")),
body: Center(
child: ElevatedButton(
child: Text("Go Back"),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}
Named Routes for Cleaner Navigation
For larger apps, named routes offer better structure.
Define routes in MaterialApp:
dart
Copy
Edit
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/about': (context) => AboutPage(),
},
)
Navigate using:
dart
Copy
Edit
Navigator.pushNamed(context, '/about');
Conclusion
Flutter provides flexible options for navigation, from simple route pushing to structured named routing. Mastering these techniques allows you to create smooth, user-friendly navigation flows in your apps. Whether you're developing small apps or large, scalable projects, understanding routing is a must-have skill in your Flutter toolkit.
Learn Flutter Training in Hyderabad
Read More:
Stateful vs Stateless Widgets in Flutter Explained
Flutter Layout Basics: Rows, Columns, and Containers
Building Responsive UI in Flutter for Multiple Screen Sizes
Working with Lists and Grids in Flutter
Visit our IHub Talent Training Institute
Comments
Post a Comment