Navigation in Flutter

Haider Ali
Complete Flutter Guide
2 min readMay 27, 2024

In Flutter, navigating between different screens is crucial for creating a user-friendly app. These screens, also called routes, are essentially widgets that define what the user sees. Flutter offers a built-in navigation system using the Navigator class. This system allows you to push new routes onto a stack, effectively transitioning to new screens, and pop routes from the stack to return to previous ones.

To start navigating between pages, you use the Navigator.push, pushNamed, and pop methods.

Example

main.dart

import 'package:flutter/material.dart';
import 'pages/home.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {

return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Mobile App Development'),
);
}
}

home.dart

import 'package:cs06/pages/about.dart';
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(child: Text("Navigation Demo",
style: TextStyle(fontSize: 30),),),
Container(child: Text("Main Screen"),),
SizedBox(height: 20,),
ElevatedButton(onPressed: aboutScreen, child: Text("About"))
],
),
)
);
}

void aboutScreen() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const
AboutPage(title: "About me!")),
);
}
}

about.dart

import 'package:flutter/material.dart';

class AboutPage extends StatefulWidget {
const AboutPage({super.key, required this.title});
final String title;

@override
State<AboutPage> createState() => _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(child: Text("About Screen"),),
SizedBox(height: 20,),
ElevatedButton(onPressed: gotoHome,
child: Text("Back to main!"))
],
),
)
);
}

void gotoHome() {
Navigator.pop(context);
}
}
Home screen
About Screen

--

--