0% found this document useful (0 votes)
5 views

flutter - routing

Uploaded by

ahmadroheed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

flutter - routing

Uploaded by

ahmadroheed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Slide 1: Title Slide

7. Navigation and Routing in Flutter


Navigation and routing are crucial aspects of app development in Flutter.
Flutter, being an open source mobile app framework, provides a variety of
options for app navigation and routing. In this article, we will discuss in detail
about navigation and routing in Flutter, from the basics to the advanced
ones.

Slide 2: Definition of Navigation & Routing

To begin with, navigation is the process of transitioning between different


pages (also known as routes) within an application. Routing, on the other
hand, is a mechanism that allows developers to define the structure and flow
of the application. In other words, navigation is about "how" to move
between pages, while routing is about "what" exactly those pages are.

Slide 3: Basic Navigation in Flutter

In Flutter, the Navigator class is used to navigate between routes. The


Navigator works like a stack, where routes are stacked on top of each other.
When a new path is browsed, it is pushed onto the browser stack. And when
the user goes back, the current route is popped from the stack.

To navigate to a new route, you can use the Navigator.push method, passing
in the current context and the route you want to navigate to. To go back to
the previous route, you can use the Navigator.pop method.
Slide 4: Named Routing in Flutter

In larger applications, it can be difficult to manage multiple routes and


navigation between them. This is where named routing can come in handy.
With named routing, you can define all your routes in one place and refer to
them by name.

To use named routing, you need to define a String Map and WidgetBuilder in
the MaterialApp or CupertinoApp. Each Map key is the name of the route and
the corresponding value is the function that will build that route.

Slide 5: Generated Routing in Flutter

Generated routing is a more advanced routing technique in Flutter. It allows


you to define routes dynamically based on some logic or condition. For
example, you might want to show an error page when an unknown route is
navigated.

To use generated routing, you need to provide a function for the


onGenerateRoute parameter of the MaterialApp or CupertinoApp. This
function will be called whenever the Navigator is asked to navigate to a route
with the pushNamed method.

Slide 6: Passing Arguments & Custom Transitions


Passing Arguments Between Routes
Occasionally, you may want to pass some data from one route to another.
This can easily be done in Flutter. When navigating to a new route, you can
pass any object to the push method arguments argument.

Routing Custom Transitions


Finally, Flutter also allows you to customize routing transitions. By default,
Flutter uses a slide transition for iOS and a fade transition for Android.
However, you can override this by providing your own transition function for
the transitionsBuilder parameter of the MaterialPageRoute or
CupertinoPageRoute.

Slide 7: Summary Slide

In summary, navigation and routing are fundamental aspects of application


development in Flutter. They allow you to define the structure and flow of
your application and provide a great user experience. Therefore, it is
important to understand and master these concepts to become an effective
Flutter developer.

Slide 8: 7.1. Navigation and Routing in Flutter: Introduction


to Routing in Flutter

To develop complex and dynamic applications in Flutter, it is essential to


understand the concept of navigation and routing. In this context, routing
refers to the transition between different pages, or 'routes', within an
application. Flutter offers a flexible and intuitive approach to managing these
transitions, allowing developers to create rich and engaging user
experiences.
Navigation in Flutter is based on the route stack idea. Each route is an
independent screen. When a new route is navigated, it is stacked on top of
the stack. When the user comes back, the route on top of the stack is
removed. This is a common approach to navigation that can be found on
many operating systems, from desktop systems to mobile systems.

Slide 9: MaterialApp Widget and Route Definition

To start using navigation and routing in Flutter, you need to understand the
concept of 'MaterialApp Widget'. This is a convenience widget that wraps
around various widgets that are commonly needed by applications. It builds
on a WidgetsApp widget adding material-design specific functionality. This
widget is where you define your routes and provide context for the rest of
your app.

Routes in Flutter are defined using a Dart Map. The key is a string that
identifies the route, and the value is a function that returns a widget that will
be displayed when that route is navigated. For example:

Copy
Download
MaterialApp(
routes: {
'/': (context) => HomeScreen(),
'/detail': (context) => DetailScreen(),
},
);

With this code, when the application starts, the '/' route is loaded, showing
the HomeScreen. If the user navigates to '/detail', the DetailScreen will be
displayed.
Slide 10: Navigating Between Routes

To navigate to a new route, you can use the Navigator.push() method. This
method stacks a new route on top of the route stack. It takes two arguments:
a context and a Route object. The Route object defines the route that will be
stacked. Here is an example of how you can navigate to the '/detail' route:

Copy
Download
Navigator.push(context, MaterialPageRoute(builder: (context) =>
DetailScreen()));

To go back to the previous route, you can use the Navigator.pop() method.
This method removes the top route from the stack, revealing the route below
it. Here is an example of how you can go back to the previous route:

Copy
Download
Navigator.pop(context);

Slide 11: Passing Arguments Between Routes

In addition, Flutter provides the ability to pass arguments to routes. This is


useful when you need to pass data from one screen to another. To do this,
you can pass arguments as part of the Route object. Here is an example of
how you can pass arguments to the '/detail' route:

Copy
Download
Navigator.push(context, MaterialPageRoute(
builder: (context) => DetailScreen(),
settings: RouteSettings(
arguments: 'Hello, DetailScreen!',
),
));

Then, in the DetailScreen, you can access the arguments using the
ModalRoute.of() method. Here is an example of how you can do this:

Copy
Download
final args = ModalRoute.of(context).settings.arguments;

Slide 12: Summary of Routing Concepts

In summary, navigation and routing in Flutter is an essential part of


application development. They allow you to manage the transition between
different screens in your application efficiently and intuitively. With a proper
understanding of these concepts, you can build more complex and dynamic
applications that deliver a rich and engaging user experience.

Slide 13: 7.2. Navigation and Routing in Flutter: Cross-


screen Navigation

Navigation and routing are crucial elements in any application. In Flutter,


they play a vital role in providing an optimal user experience. This article
discusses navigation and routing in Flutter, focusing on cross-screen
navigation. Let's start with a basic understanding.

Slide 14: Basic Navigation Concept in Flutter

In Flutter, everything is a widget. So each 'screen' in your app is just a


widget. Navigation between these widgets (or screens) is accomplished
using a stack, similar to the stack pattern in data structures. Each time a
new widget is opened it is pushed onto this stack. And when the user finishes
interacting with a widget and comes back, the widget is popped off the
stack. This is the basic concept of navigation in Flutter.

Slide 15: Navigating to a New Screen

To navigate to a new screen, you need to use the 'Navigator.push' method


provided by Flutter. This method takes two arguments: the current context
and the route to the new screen. The route is usually created using the
'MaterialPageRoute' method, which takes an argument from the constructor -
the widget you want to open.

For example:

Copy
Download
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);

The code above opens a new widget called 'SecondScreen'. The 'context'
here is the current context of the widget. It is passed to 'MaterialPageRoute'
so it knows where to place the new widget in the widget tree.

Slide 16: Returning to Previous Screen

To go back to the previous screen, you can use the 'Navigator.pop' method.
This method removes the current widget from the stack and returns to the
previous widget. You can use this method when the user has finished
interacting with the current widget. For example, you can call 'Navigator.pop'
when the user presses a back button.

Slide 17: Passing Data Between Screens

In addition, Flutter also provides a way to pass data between widgets during
navigation. You can pass the data as an argument to the constructor of the
widget you are opening. For example:

Copy
Download
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(data: 'Hello, World!'),
),
);

The code above passes a string 'Hello, World!' to 'SecondScreen'. In


'SecondScreen', you can access this data through the constructor argument.

Slide 18: Named Routing in Flutter

In addition to basic navigation, Flutter also supports named routing. In


named routing, you define a route table with route names and their
respective widgets. You can then navigate to a widget using its route name.
This is useful when you have many screens in your app and navigation
becomes complex.
For example, you can define a route table like this:

Copy
Download
final routes = {
'/': (context) => HomeScreen(),
'/second': (context) => SecondScreen(),
};

You can then navigate to 'SecondScreen' using its route name:

Copy
Download
Navigator.pushNamed(context, '/second');

Slide 19: Summary of Cross-screen Navigation

In short, navigation and routing in Flutter is simple yet powerful. They allow
you to manage navigation between screens in an efficient and organized
way. In addition, they offer the flexibility to pass data between screens and
use named routing to handle navigation complexity.

When building apps with Flutter, it's important to understand navigation and
routing to provide a smooth and intuitive user experience. So make sure you
take the time to learn and experiment with these concepts.

Slide 20: 7.3. Navigation and Routing in Flutter: Passing


Parameters Between Screens

Navigation and routing are essential components of building multiscreen


applications. Flutter, with its Dart language, provides an efficient and
effective way to manage navigation and routing in your apps. Let's dive deep
into the subject and understand how passing parameters between screens
can be accomplished in Flutter.
Slide 21: Navigator Class Basics

In Flutter, navigation and routing are handled by a class called Navigator.


The Navigator works like a stack, where each route (or screen) is stacked
one on top of the other. When a user opens an application, the first screen
they see is called the home or "home" route. From there, each new screen
the user navigates to is stacked on top of the initial route.

Slide 22: Passing Parameters to New Screens

Passing parameters between screens in Flutter is a simple and


straightforward process. Parameters are passed as arguments to the
Navigator.push() function. The push() function accepts two parameters: the
current context and the new route. The new route is an instance of
MaterialPageRoute, which in turn takes a builder parameter. The builder
parameter is a function that returns a new widget, which is the new screen
the user will be navigated to.

For example, if we want to pass a "username" parameter to a new screen,


we can do it as follows:

Copy
Download
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(username: 'John Doe'),
),
);
In the example above, we are passing the "username" parameter to the new
screen "NewScreen". The parameter is then accessed on the new screen
using the widget.username syntax.

Slide 23: Returning Data to Previous Screens

In addition to passing parameters to new screens, Flutter also allows data to


be passed back from the new screen to the previous screen. This is done
using the Navigator.pop() function. The pop() function accepts two
parameters: the current context and the data to be returned.

For example, if we want to return a "success" value from the new screen to
the previous screen, we can do it like this:

Copy
Download
Navigator.pop(context, 'success');

Slide 24: Handling Returned Data

The returned value can then be accessed on the previous screen using the
Navigator.push() function.

For example, we can do something like:

Copy
Download
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(username: 'John Doe'),
),
);

if (result == 'success') {
// Do something
}

In the example above, we are expecting a return value from the new screen.
If the returned value is "success", then we do something.

Slide 25: Summary of Parameter Passing

In short, navigation and routing in Flutter is handled by the Navigator class,


which works like a stack. Passing parameters between screens is done
through the Navigator.push() and MaterialPageRoute() functions, while
passing data back to the previous screen is done through the
Navigator.pop() function.

With these tools in hand, you can create complex and advanced Flutter
applications with multiple screens and passing parameters between them.
Navigation and routing are fundamental to building Flutter apps, and
understanding how they work is essential to becoming an effective Flutter
developer.

Slide 26: 7.4. Navigation and Routing in Flutter: Navigation


with Named Routes

Navigation and routing are fundamental aspects of application development.


In Flutter, navigation and routing is handled by a navigation object that has a
stack of widgets that can be manipulated to navigate between pages. One of
the most efficient ways to handle navigation in Flutter is through the use of
named routes.

Slide 27: Understanding Named Routes

Named routes are essentially strings that are used to identify a page or
screen in a Flutter app. They are useful because they allow you to navigate
to a page without needing to have a direct reference to it. This makes the
code easier to maintain and more flexible, as you can change a page's
implementation without having to change all the places the page is
referenced.

Slide 28: Defining Named Routes

To start using named routes in Flutter, you need to define a route map in the
MaterialApp or WidgetsApp object. This route map is a dictionary where the
keys are strings representing the route names and the values are functions
that return the widget that should be displayed when the route is navigated.

For example, you might have a route map that looks like this:

Copy

Download

{
'/': (context) => HomePage(),
'/detail': (context) => DetailPage(),
}
Here, the '/' route corresponds to the HomePage and the '/detail' route
corresponds to the DetailPage.

Slide 29: Navigating with Named Routes

You can navigate to these pages using the Navigator.pushNamed method,


passing the context and route name as arguments.

For example, to navigate to the DetailPage, you would do this:

Copy

Download

Navigator.pushNamed(context, '/detail');

This will push the DetailPage to the top of the navigation stack and display it.

Slide 30: Passing Arguments with Named Routes

If you want to pass arguments to the page, you can pass them as a third
argument to the pushNamed method. For example, if you wanted to pass an
Item object to the DetailPage, you would do this:

Copy

Download

Navigator.pushNamed(context, '/detail', arguments: item);


Slide 31: Accessing Route Arguments

On the DetailPage, you can then access the arguments using the
ModalRoute.of method to get the current route and then access the
arguments property. For example:

Copy

Download

final item = ModalRoute.of(context).settings.arguments as Item;

This will fetch the Item object you passed as an argument when you
navigated to the page.

Slide 32: Benefits of Named Routes

Named routes make navigation in Flutter much more manageable and


flexible. They allow you to:

 Define all your routes in one place

 Make routes easier to maintain and change

 Pass route names as arguments

 Store routes in variables

 Generate routes dynamically

Slide 33: Summary of Named Routes


In short, navigation and routing is an essential part of Flutter app
development, and using named routes can greatly simplify this process. By
understanding how to use named routes, you can make your code more:

 Maintainable

 Flexible

 Easier to navigate

Slide 34: 7.5. Navigation and Routing in Flutter: Navigation


with Dynamic Routes

Navigation and routing are crucial aspects in the development of any


application. In Flutter, these concepts are incorporated into the framework
quite effectively, allowing developers to create fluid and intuitive user
experiences. This article will cover navigation and routing in Flutter, with a
focus on navigation with dynamic routes.

Slide 35: Navigator Class and Route Stack

Flutter provides a class called Navigator to manage routes in an application.


The Navigator works like a route stack, where you can "push" new routes
onto the stack or "pop" existing routes. This allows for easy and intuitive
navigation between the different application screens.
Slide 36: Creating Dynamic Routes

To create a dynamic route in Flutter, you need to use the 'onGenerateRoute'


function. This function is called whenever the application needs to navigate
to a new route that has not been previously defined. The 'onGenerateRoute'
function takes a RouteSettings object as an argument, which contains
information about the route being created, such as the name of the route
and any arguments that can be passed to the route.

Slide 37: Dynamic Route Example

Here is an example of how you can use the 'onGenerateRoute' function to


create dynamic routes:

Copy
Download
onGenerateRoute: (settings) {
if (settings.name == '/detail') {
final DetailArgs args = settings.arguments;

return MaterialPageRoute(
builder: (context) {
return DetailScreen(args);
},
);
}
// ...
},

In this example, we are checking that the route name is '/detail'. If so, we
create a new route using the MaterialPageRoute class and pass the
arguments to the DetailScreen screen.
Slide 38: Benefits of Dynamic Routes

Dynamic routes are extremely powerful as they allow you to:

 Create routes based on your application's needs


 Pass dynamic arguments (like product IDs) to routes
 Fetch data based on route arguments
 Create routes that depend on application state
 Implement conditional navigation (e.g., authentication checks)

Slide 39: Practical Applications

Dynamic routes enable scenarios such as:

 Product detail pages that fetch data based on product ID


 User profile pages that load different content
 Routes that only accessible to authenticated users
 Conditional redirects based on app state
 Dynamic error handling for unknown routes

Slide 40: Summary of Dynamic Routing

In short, navigation and routing are key aspects in Flutter app development.
By understanding how to use:

 The Navigator class


 The 'onGenerateRoute' function
 RouteSettings object
 Dynamic arguments
You can create fluid and intuitive navigation that adapts to your application's
needs, making your app more flexible and user-friendly.

Slide 41: Conclusion

I hope this article has given you a good overview of how navigation and
routing work in Flutter. With a little practice, you'll be able to build Flutter
apps with complex navigation and routing with ease.

Slide 42: 7.6. Navigation and Routing in Flutter: Navigation


History Management

Navigation and routing are fundamental aspects of application development.


They allow users to move between different screens and perform different
actions. In Flutter, navigation history management is done through a stack of
routes, where each route represents a new screen or page. Flutter uses the
Dart package 'dart:ui' to manage this stack of routes.

Slide 43: Understanding Routes in Flutter

To begin with, it's important to understand the concept of routes in Flutter. A


route is an abstraction for a "screen" or "page" of an application. In Flutter,
routes are represented by widgets. Each route you navigate is stacked on
top of the route stack. The route at the top of the stack is the currently
active route.
Slide 44: Navigating to New Routes

To navigate to a new route, you can use the Navigator.push method. This
method adds the specified route to the top of the route stack. Flutter
automatically animates the transition to the new route for you. Here is an
example of how you can use Navigator.push:

Copy
Download
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);

This will cause Flutter to create the SecondRoute widget and animate it on
the screen, overlaying the current route.

Slide 45: Returning to Previous Routes

When you want to go back to the previous route, you can use the
Navigator.pop method. This method removes the top route from the stack
and returns to the previous route. Here is an example of how you can use
Navigator.pop:

Copy
Download
Navigator.pop(context);

This will cause Flutter to pop the current route from the stack and return to
the previous route, animating the transition for you.
Slide 46: Clearing Navigation History

In some cases, you may want to navigate to a route and remove all previous
routes from the stack. To do this, you can use the
Navigator.pushAndRemoveUntil method. This method pushes the specified
route to the top of the stack and removes all other routes until the given
condition is satisfied. Here is an example of how you can use
Navigator.pushAndRemoveUntil:

Copy
Download
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
(Route route) => false,
);

This will cause Flutter to create the SecondRoute widget, animate it on the
screen, and remove all other routes from the stack.

Slide 47: Named Routes Implementation

Flutter also provides a way to define named routes. Named routes are useful
when you need to navigate to a route from multiple places in your app. To
define a named route, you can use the onGenerateRoute parameter of the
MaterialApp or CupertinoApp widget. Here is an example:

Copy
Download
MaterialApp(
onGenerateRoute: (settings) {
if (settings.name == '/second') {
return MaterialPageRoute(builder: (context) => SecondRoute());
}
},
);

Slide 48: Navigating to Named Routes

To navigate to a named route, you can use the Navigator.pushNamed


method. This method pushes the route with the specified name to the top of
the stack. Here is an example:

Copy
Download
Navigator.pushNamed(context, '/second');

Slide 49: Summary of Navigation History Management

In short, navigation and routing in Flutter is managed through a route stack.


Each route represents a "screen" or "page" of an application. You can:

 Navigate to new routes using Navigator.push


 Return to previous routes using Navigator.pop
 Clear history using Navigator.pushAndRemoveUntil
 Use named routes for consistent navigation
 Define routes in MaterialApp configuration
Slide 50: 7.7. Navigation and Routing in Flutter: Tabbed
Browsing

Navigation and routing are vital elements in any application as they allow
users to move between different pages or screens. In Flutter, navigation and
routing is mainly handled by the 'Navigator' widget and the 'PageRoute'.
However, for a more personalized and streamlined experience, Flutter also
offers tabbed browsing. Let's explore this in detail.

Slide 51: Understanding Tabbed Browsing in Flutter

Tabbed navigation is a common approach to organizing the user interface in


mobile apps. It allows users to switch between different screens or sections
of an application by tapping an icon or tab title at the bottom or top of the
screen. In Flutter, this is facilitated through a set of widgets, including the
'TabController', 'TabBar' and 'TabBarView'.

Slide 52: TabController

The TabController is an object that coordinates the selection of tabs and the
animation of sliding between tabs. It is normally created once and passed to
the 'TabBar' and 'TabBarView' widgets that use it. The TabController can be
created using the default constructor or using the 'of' method to retrieve an
existing TabController.
Slide 53: TabBar

The TabBar is a widget that displays a horizontal row of tabs. It is usually


placed at the top of the screen or at the bottom of the AppBar. Each tab is
represented by a widget, which can be an icon, text, or both. When a user
taps a tab, the TabBar tells the TabController, which then makes the
corresponding tab active.

Slide 54: TabBarView

The TabBarView is a widget that displays the content of the current tab. It
uses the TabController to switch between different tabs when the user taps a
tab on the TabBar. Each tab in the TabBarView is represented by a widget,
which is created when the tab becomes active and destroyed when it is
replaced by another tab.

Slide 55: Implementing Tabbed Browsing

To implement tabbed browsing in Flutter, you need to follow these steps:

1. Create a TabController passing the number of tabs and the vsync, which is
normally 'this'.
2. Create a TabBar and pass the TabController to it. Define tabs using the 'tabs'
property and the widgets that represent each tab.
3. Create a TabBarView and pass the TabController to it. Define the content of
each tab using the 'children' property and the widgets representing the
content of each tab.
4. Wrap the TabBar and TabBarView with a Scaffold or AppBar widget to display
the TabBar at the top of the screen.

It is important to remember that the TabController, TabBar and TabBarView


must be used together to ensure that the tab selection and swiping
animation are correctly coordinated.

Slide 56: Conclusion

Tabbing navigation is an effective way to organize the user interface in


mobile applications. In Flutter, this is facilitated through a set of widgets that
allow you to create a personalized and optimized tabbed browsing
experience. With the right knowledge and practice, you can use tabbed
browsing to improve the usability and user experience in your Flutter apps.

Slide 57: 7.8. Navigation and Routing in Flutter: Drawer


Navigation

One of the most important elements in any application is navigation.


Navigation allows users to move from page to page without getting lost. In
Flutter, navigation can be accomplished in several ways, one of which is
using the drawer. The drawer is a sliding panel that contains links to other
parts of the app. This article will discuss how to implement drawer navigation
in Flutter.
Slide 58: Introduction to Flutter and Dart

Flutter is an open source framework created by Google for developing


applications for mobile devices. It allows developers to build high-
performance Android and iOS apps from a single code base. Dart is the
programming language used to write Flutter code.

Slide 59: What is Navigation and Routing in Flutter?

Navigation is the process of moving between different pages in an


application, while routing is the process of defining the path that the
navigation should take. In Flutter, navigation and routing are handled by a
Navigator object and routes. Each application screen is represented by a
route, and the Navigator is responsible for moving between routes.

Slide 60: Drawer Navigation Overview

A drawer is a popular form of navigation in mobile apps. It's a sliding panel


that moves from the left or right edge of the screen and usually contains
links to the main sections of the application. In Flutter, a drawer can be
created using the Drawer widget.

Slide 61: Implementing Drawer Navigation - Step 1

4.1. Create a Drawer widget


First, you need to create a Drawer widget. The Drawer widget can contain
any type of widget, but it usually contains a ListView widget. The ListView
allows you to create a list of items, which can be used to represent links to
other pages.

Slide 62: Implementing Drawer Navigation - Step 2

4.2. Add the Drawer widget to the Scaffold


The next step is to add the Drawer widget to the Scaffold. Scaffold is a layout
widget that implements the basic material design framework. It has a
property called drawer, where you can add the Drawer widget.

Slide 63: Implementing Drawer Navigation - Step 3

4.3. Create the routes


After adding the Drawer to the Scaffold, you need to create the routes to the
different pages in your application. Each route is represented by a widget,
which is the page that will be shown when the route is navigated.

Slide 64: Implementing Drawer Navigation - Step 4

4.4. Navigate to Routes


Finally, you can navigate to routes by tapping items in the Drawer. To do
this, you need to use the Navigator.pushNamed method, which takes the
context and route name as arguments.
Slide 65: Conclusion on Drawer Navigation

Drawer navigation is an effective way to let users move between different


pages of a Flutter app. With the use of Drawer widget and Navigator object,
you can easily implement drawer navigation in your Flutter app.

It is important to remember that navigation and routing are crucial aspects


of application development. They allow users to interact with the application
intuitively and efficiently. Therefore, it is essential that you implement
navigation and routing correctly in your Flutter application.

Slide 66: Practical Implementation Example

Here's a basic code example for implementing drawer navigation:


dart

Copy

Download

Scaffold(
drawer: Drawer(
child: ListView(
children: [
ListTile(
title: Text('Home'),
onTap: () {
Navigator.pushNamed(context, '/home');
},
),
ListTile(
title: Text('Settings'),
onTap: () {
Navigator.pushNamed(context, '/settings');
},
),
],
),
),
body: Center(child: Text('Main Content')),
)

Slide 67: 7.9. Navigation and Routing in Flutter: Navigation


with Bottom Navigation Bar

One of the most crucial aspects of application development is the ability to


navigate between different screens and sections. In Flutter, this functionality
is provided through the concept of routing and navigation. In this context,
let's focus on one of the most common components used for navigation - the
Bottom Navigation Bar.

Slide 68: Bottom Navigation Bar Overview

The Bottom Navigation Bar is a horizontal navigation bar that is usually


placed at the bottom of an application. It allows users to switch between
different sections of the app with a single tap. This bottom navigation bar is
commonly used in large scale applications where navigation between
different sections is required.

Slide 69: Implementation Steps


How to implement navigation with Bottom Navigation Bar
To implement Bottom Navigation Bar navigation in Flutter, we first need to
define a Bottom Navigation Bar in our app. To do this, we can use Flutter's
BottomNavigationBar widget. This widget receives a list of items
(BottomNavigationBarItem) that represent the different sections of the
application.

Slide 70: Setting Up State

First, we need to set a state for the current page index. This state will
change each time a new item is selected in the bottom navigation bar.
dart

Copy

Download

int _currentIndex = 0;

Slide 71: Defining Pages

Next, we define the list of pages that represent the different sections of the
application. Each page is represented by a widget.
dart

Copy

Download

final List<Widget> _pages = [


HomePage(),
SearchPage(),
ProfilePage(),
];

Slide 72: Creating the BottomNavigationBar

Next, we define the bottom navigation bar within the build method of the
main widget. Here, we define the bottom navbar items and handle the page
change logic when an item is selected.
dart

Copy

Download

BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
Slide 73: Displaying Current Page

Finally, we display the current page in the body of the main widget. We use
the _currentIndex state to determine which page to display.
dart

Copy

Download

body: _pages[_currentIndex],

Slide 74: Complete Example

Here's a complete example of implementing bottom navigation:


dart

Copy

Download

class MyApp extends StatefulWidget {


@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


int _currentIndex = 0;

final List<Widget> _pages = [


HomePage(),
SearchPage(),
ProfilePage(),
];

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label:
'Search'),
BottomNavigationBarItem(icon: Icon(Icons.person), label:
'Profile'),
],
),
),
);
}
}

Slide 75: Conclusion

Navigation with Bottom Navigation Bar is an essential part of app


development in Flutter. It allows users to easily switch between different
sections of the application, improving the user experience. With Flutter,
implementing Bottom Navigation Bar navigation is easy and straightforward,
thanks to the BottomNavigationBar widget and the flexibility of Flutter's
routing system.

To create more complex and advanced applications, you can combine


Bottom Navigation Bar navigation with other routing and navigation
techniques, such as drawer navigation, tabbed navigation, and stack
navigation. This will allow you to build applications with richer navigation and
a more immersive user experience.

In conclusion, navigation and routing are crucial aspects of Flutter app


development, and mastering these concepts is essential to becoming a
competent Flutter developer.

Slide 76: 7.10. Navigation and Routing in Flutter: Navigation


with PageView

Navigation and routing are crucial aspects of Flutter app development. They
allow for smooth transition between screens and the implementation of an
intuitive user experience. One of the most effective ways to implement
navigation in Flutter is using PageView. This article will discuss how to
implement navigation and routing in Flutter using PageView.

Slide 77: PageView Overview

PageView is a scroll widget that automatically creates a scrolling view of


pages. It allows users to navigate between pages by swiping left or right.
Furthermore, PageView provides an efficient way to create a slide layout
between screens in your Flutter app.

Slide 78: What is PageView?

PageView is a Flutter widget that creates scrolling pages. It creates a


scrolling list that works page by page. Each child of a PageView is forced to
be the same size as the viewport. You can customize the appearance and
behavior of the PageView to suit your needs.

Slide 79: Implementation Step 1 - Creating a PageView

To use PageView for navigation and routing in Flutter:

1. Create a new PageView widget using the PageView constructor. Example:

dart

Copy
Download
PageView(
children: [
Container(color: Colors.red),
Container(color: Colors.blue),
Container(color: Colors.green),
],
)

In this example, we create a PageView with three pages. Each page is a


Container widget with a different color.

Slide 80: Implementation Step 2 - Using PageView Controller

2. Use the PageView controller to control which page is displayed:

dart

Copy
Download
PageController controller = PageController(initialPage: 0);

PageView(
controller: controller,
children: [
Container(color: Colors.red),
Container(color: Colors.blue),
Container(color: Colors.green),
],
)

We create a PageController and pass it to the PageView. The controller


allows jumping to specific pages using jumpToPage or animateToPage methods.

Slide 81: Implementation Step 3 - Navigating Between Pages

3. Navigate between pages using swipe or controller methods:

dart

Copy
Download
controller.animateToPage(
2,
duration: Duration(seconds: 1),
curve: Curves.easeIn
);

This moves to the third page with a 1-second animation using an ease-in
curve.

Slide 82: Complete PageView Example

Here's a complete implementation example:


dart

Copy
Download
class MyPageView extends StatefulWidget {
@override
_MyPageViewState createState() => _MyPageViewState();
}

class _MyPageViewState extends State<MyPageView> {


final PageController _controller = PageController(initialPage: 0);

@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _controller,
children: [
Center(child: Text('Page 1', style: TextStyle(fontSize: 24))),
Center(child: Text('Page 2', style: TextStyle(fontSize: 24))),
Center(child: Text('Page 3', style: TextStyle(fontSize: 24))),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller.nextPage(
duration: Duration(milliseconds: 500),
curve: Curves.ease,
);
},
child: Icon(Icons.arrow_forward),
),
);
}
}

Slide 83: Conclusion

PageView is a powerful tool for implementing navigation and routing in


Flutter apps:

 Creates intuitive swipe navigation between screens


 Provides smooth animated transitions
 Offers programmatic control via PageController
 Can be combined with other navigation patterns
 Highly customizable for different use cases

With PageView, you can create engaging, app-like navigation experiences in


your Flutter applications.

Slide 84: 7.11. Navigation and Routing in Flutter: Stack


Navigation

Navigation and routing are an integral part of any modern app, and Flutter is
no exception. Flutter makes it easy to create beautiful user interfaces with a
rich set of pre-built widgets, but it also offers a powerful navigation and
routing system to manage how users move around your app. In this article,
we're going to explore the concept of "Stack Navigation" in Flutter.

Slide 85: Understanding Stack Navigation

In Flutter, navigation between different screens or pages in the application is


handled by something called a "Navigator", which works very similarly to a
stack in computer science. Whenever a new script (or page) is opened, it is
"pushed" to the top of the stack. When a script is closed, it is "unstacked"
and removed from the stack. This is called "Stack Navigation".

The advantage of this system is that it allows for an intuitive and easy-to-
manage navigation flow. You can easily get back to the previous page simply
by popping the current script, and you always have a clear reference to the
"previous page" in the form of the script at the top of the stack.
Slide 86: Implementing Stack Navigation

To start using stack navigation in Flutter, you will need to use the 'Navigator'
class. The 'Navigator' class has two main methods you'll use to manage your
navigation: 'push' and 'pop'.

The 'push' method is used to open a new script. It receives a 'Route' object
that describes the page you want to open. There are several ways to create
a 'Route' object, but the most common is to use the 'MaterialPageRoute'
class, which creates a route that transitions to the new page using a material
design transition animation.

The 'pop' method, on the other hand, is used to close the current script and
move back to the previous one on the stack. It does not require any
arguments as it simply removes the script at the top of the stack.

Slide 87: Stack Navigation Example

Let's take a look at an example of how you can use stack navigation in
Flutter. Suppose you have two pages in your application, 'HomePage' and
'DetailPage', and you want to allow the user to navigate between them.

First, you'll need to define your routes. This is done in your app's
'MaterialApp' object, which has a 'routes' property that takes a map of route
names to route builder functions. Here is how you can define your routes:
dart

Copy

Download
MaterialApp(
routes: {
'/': (context) => HomePage(),
'/detail': (context) => DetailPage(),
},
);

Slide 88: Navigating Between Pages

You can then use the 'Navigator.pushNamed' method to navigate to the


'DetailPage' from the 'HomePage'. Here's how you can do that:
dart

Copy

Download

Navigator.pushNamed(context, '/detail');

Finally, to get back to the 'HomePage' from the 'DetailPage', you can use the
'Navigator.pop' method. Here's how:
dart

Copy

Download

Navigator.pop(context);

Slide 89: Complete Stack Navigation Example

Here's a complete implementation example:


dart

Copy
Download

void main() {
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailScreen(),
},
));
}

class HomeScreen extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: Center(
child: ElevatedButton(
child: Text('View Details'),
onPressed: () {
Navigator.pushNamed(context, '/details');
},
),
),
);
}
}

class DetailScreen extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Details')),
body: Center(
child: ElevatedButton(
child: Text('Go Back'),
onPressed: () {
Navigator.pop(context);
},
),
),
);
}
}

Slide 90: Conclusion

In summary, stacked navigation in Flutter is an effective way to manage the


navigation flow in your application. With the 'Navigator' class and its 'push'
and 'pop' methods, you can easily open new pages and go back to previous
pages. While the idea of stack-based browsing may take some getting used
to, once you get the hang of it, you'll find that it offers a great deal of
flexibility in creating intuitive and enjoyable user experiences.

Slide 91: 7.12. Navigation and Routing in Flutter: Navigation


with Push/Pop

Navigation and routing are fundamental aspects of application development.


In Flutter, these features are implemented through a concept called
"Navigator" that works like a stack, where the different routes or pages of
the application are stacked on top of each other. In this context, let's discuss
push/pop navigation in Flutter.

Slide 92: Understanding Push/Pop Navigation

Push/pop navigation is a fundamental concept in building apps using Flutter.


The 'push' method is used to add a new route to the Navigator's route stack.
On the other hand, the 'pop' method is used to remove the current route
from the Navigator stack.
To understand this better, imagine an application with three screens: Screen
A, Screen B, and Screen C. When the application starts, Screen A is pushed
onto the Navigator stack. If the user navigates to Screen B, that screen is
pushed onto the stack, being above Screen A. Now, if the user decides to go
to Screen C, that screen is also pushed onto the stack, being on top. So the
Navigator stack order is: Screen A, Screen B, and Screen C.

If the user decides to go back to Screen B, Screen C is popped from the


Navigator stack, leaving Screen B on top. If the user goes back to Screen A,
Screen B is popped from the stack, leaving Screen A on top. Therefore, the
'pop' method allows the user to navigate back through the application's
screens.

Slide 93: Implementing Push Navigation

To implement push navigation in Flutter, you use the 'Navigator.push'


method:
dart

Copy
Download
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScreenB())
);

This code pushes Screen B onto the Navigator stack. The 'context' is a
reference to the location in the widget tree where this call is made. The
'MaterialPageRoute' is a route that uses a material design based page
transition to switch screens.
Slide 94: Implementing Pop Navigation

To implement pop navigation in Flutter, you use the 'Navigator.pop' method:


dart

Copy
Download
Navigator.pop(context);

This code removes the current route from the Navigator stack, allowing the
user to go back to the previous screen.

Slide 95: Complete Push/Pop Example

Here's a complete implementation example:


dart

Copy
Download
class ScreenA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Screen A')),
body: Center(
child: ElevatedButton(
child: Text('Go to Screen B'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScreenB()),
);
},
),
),
);
}
}

class ScreenB extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Screen B')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text('Go to Screen C'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScreenC()),
);
},
),
SizedBox(height: 20),
ElevatedButton(
child: Text('Back to Screen A'),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
);
}
}

Slide 96: Advanced Push/Pop Features


Flutter's push/pop navigation also supports:

 Passing data between screens using route arguments


 Returning data from popped screens
 Custom transition animations
 Route guards and interceptors
 Deep linking integration

Slide 97: Conclusion

In summary, push/pop navigation is an effective way to manage navigation


between the different screens of a Flutter app. By pushing a new route onto
the Navigator stack, you can take the user to a new screen. By removing the
current route from the stack, you can allow the user to go back to the
previous screen. Understanding these concepts is critical to building
functional and easy-to-use Flutter apps.

It's important to remember that navigation and routing is just one part of
Flutter app development. In addition, you also need to focus on other
aspects like the user interface, application logic, and interaction with APIs
and databases. However, with practice and experience, you will be able to
build complete and advanced Flutter applications.

Slide 98: 7.13. Navigation and Routing in Flutter: Navigation


with Optional Parameters

Navigation and routing are essential parts of application development. In


Flutter, navigation and routing are managed with the help of the Navigator
widget and routes. Navigation refers to the process of moving between
different screens in an application, while routing refers to mapping URLs or
other identifiers to specific screens. This chapter will cover navigation with
optional parameters in Flutter.

Slide 99: Understanding Optional Parameters

To begin with, it's important to understand what optional parameters are. In


Dart, optional parameters are arguments that you can pass to a function, but
aren't required. This is useful when you have a function that can accept
multiple arguments, but you only need to pass a few of them. In the context
of navigation in Flutter, optional parameters are used to pass data between
screens.

Slide 100: Navigator Widget Basics

In Flutter, navigation between screens is done through the Navigator widget.


The Navigator widget works like a stack, where you can push new routes
onto the stack and they will be displayed on the screen. When you want to
go back to the previous screen, you can pop the current route from the
stack.

Slide 101: Passing Data with Optional Parameters


To pass data between screens, you can use optional parameters. For
example, let's say you have a list of items, and when the user clicks on an
item, you want to navigate to a new screen that shows the details for that
item. You can pass the item as an optional parameter to the new route.

Here is an example of how you can do this:


dart

Copy
Download
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(item: item),
),
);

In the above function, we are pushing a new route onto the Navigator stack.
The new route is created using the MaterialPageRoute function, which
accepts a builder function. The builder function is used to build the screen
that will be displayed. In our case, we are building a DetailScreen screen and
passing the item as an optional parameter.

Slide 102: Receiving Parameters in the Destination Screen

On the DetailScreen screen, you can access the item passed as an optional
parameter as follows:
dart

Copy
Download
class DetailScreen extends StatelessWidget {
final Item item;

DetailScreen({Key key, @required this.item}) : super(key: key);


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(item.name),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(item.description),
),
);
}
}

Slide 103: Parameter Implementation Details

In the DetailScreen class:

1. We define the item as a final field that must be initialized


2. We use the class constructor to initialize the item
3. We mark the item as @required (must be provided)
4. We use the item's properties to build the UI (name in AppBar, description in
body)

Slide 104: Complete Example with Optional Parameters


dart

Copy
Download
// Item Model
class Item {
final String name;
final String description;

Item({this.name, this.description});
}

// Main Screen
class MainScreen extends StatelessWidget {
final List<Item> items = [
Item(name: 'Item 1', description: 'Description for Item 1'),
Item(name: 'Item 2', description: 'Description for Item 2'),
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Items')),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index].name),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(item: items[index]),
),
);
},
);
},
),
);
}
}

Slide 105: Summary of Optional Parameters


In summary, navigation with optional parameters in Flutter:

 Provides a clean way to pass data between screens


 Uses Dart's optional parameter syntax
 Works with both required and optional fields
 Maintains type safety through class constructors
 Enables complex data passing between routes
 Can be combined with other navigation techniques

Slide 106: Best Practices

When using optional parameters for navigation:

1. Always declare required parameters with @required


2. Use immutable data models (final fields)
3. Keep parameter lists manageable
4. Consider using named parameters for clarity
5. Document expected parameters in widget classes
6. Handle missing parameters gracefully

Slide 107: 7.14. Navigation and Routing in Flutter:


Navigation with Animations

Navigation and routing are essential parts of any application. In Flutter, this
process is simplified and efficient thanks to its powerful routing and
navigation system. In this chapter, we will explore Navigation with
animations in Flutter.
Slide 108: Navigation Basics Review

First, let's understand what navigation is. Navigation is the process of


transitioning between different pages (also known as routes) in your app.
Flutter uses Navigator to manage route stacks. A Flutter app can have
multiple instances of a Navigator, each with its own independently managed
stack of routes.

Key Methods:

 Navigator.push() - Adds new route to stack

 Navigator.pop() - Removes current route from stack

Slide 109: Routing Fundamentals

Routing is the ability to move between different pages in your application. In


Flutter:

 Defined in MaterialApp/CupertinoApp
 Each page has unique route name
 Basic implementation:

dart

Copy
Download
MaterialApp(
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailScreen(),
},
)
Slide 110: Adding Animations with page_transition

To enhance navigation with animations:

1. Add dependency to pubspec.yaml:

yaml

Copy
Download
dependencies:
page_transition: ^2.0.9

2. Import package:

dart

Copy
Download
import 'package:page_transition/page_transition.dart';

Slide 111: Implementing Animated Transitions

Wrap routes in PageTransition widget:


dart

Copy
Download
Navigator.push(
context,
PageTransition(
type: PageTransitionType.fade,
duration: Duration(milliseconds: 300),
child: DetailScreen(),
),
);
Slide 112: Animation Types

Available transition types:

 fade

 rotate

 scale

 size

 slide

 rightToLeft

 leftToRight

 topToBottom

 bottomToTop

Slide 113: Customizing Animations

Animation Duration
Controls transition length:
dart

Copy
Download
duration: Duration(milliseconds: 500) // 0.5 second animation

Animation Curves
Controls motion timing:
dart

Copy
Download
curve: Curves.easeInOut
Predefined curves: linear, decelerate, ease, easeIn, easeOut, easeInOut

Slide 114: Complete Animated Navigation Example


dart

Copy
Download
Navigator.push(
context,
PageTransition(
type: PageTransitionType.slide,
duration: Duration(milliseconds: 400),
curve: Curves.easeInOutCubic,
alignment: Alignment.bottomCenter,
child: SettingsScreen(),
),
);

Slide 115: Benefits of Animated Navigation

 Creates smoother transitions


 Enhances user experience
 Adds visual polish
 Guides user attention
 Differentiates app from competitors
 Makes navigation feel intentional

Slide 116: Best Practices


1. Keep durations between 200-500ms
2. Use consistent animation styles
3. Match animation type to context
4. Test on different devices
5. Provide visual feedback
6. Maintain 60fps performance

Slide 117: Conclusion

Navigation and routing in Flutter are simple and efficient processes. By


adding animations we can:

 Improve user experience


 Make apps more attractive
 Create enjoyable interactions
 Guide user flow
 Enhance perceived quality

Slide 118: 7.15. Navigation and Routing in Flutter: Browsing


with Authentication

Navigation and routing are key aspects of building applications. In Flutter,


navigation and routing are managed with the help of a router object.
Navigation is the process of transitioning between different pages (also
known as routes) of an application, while routing is the process of defining
the navigation logic of an application.

Slide 119: Authentication in Flutter


One of the most important parts of navigation and routing in Flutter is user
authentication. Authentication is a process that verifies that the user is who
he claims to be. This is done by prompting the user to provide valid
credentials which can be a username and password or an authentication
token. Authentication is critical to protecting sensitive user data and
maintaining application integrity.

Slide 120: Implementing Authentication

Authentication browsing in Flutter can be implemented in several ways. One


of the most common ways is using the flutter_login package. This package
provides an easy way to create a login screen and handle user
authentication. It also supports social authentication like login with Google,
Facebook, etc.

Slide 121: Adding flutter_login Dependency

To start using flutter_login, you need to add it to your project's pubspec.yaml


file:
yaml

Copy
Download
dependencies:
flutter_login: ^3.0.0 # Example version
Slide 122: LoginScreen Implementation

After adding the package, create a LoginScreen instance:


dart

Copy
Download
LoginScreen(
onLogin: (loginData) {
print('Username: ${loginData.name}');
print('Password: ${loginData.password}');
return _authUser(loginData);
},
onSignup: (loginData) {
print('Username: ${loginData.name}');
print('Password: ${loginData.password}');
return _authUser(loginData);
},
onSubmitAnimationCompleted:() {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen(),
));
},
onRecoverPassword: _recoverPassword,
)

Slide 123: Authentication Functions

Required Implementations

 _authUser: A role (function) that:

o Takes user login details


o Validates credentials
o Returns String for error messages or null for success
 _recoverPassword: A function that:

o Handles password recovery


o Sends recovery emails to users

Slide 124: Post-Authentication Navigation

After successful authentication, redirect using:


dart

Copy
Download
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomeScreen(),
)
);

This replaces the login route with the home screen in the navigation stack.

Slide 125: Alternative Authentication Packages

Other popular Flutter auth solutions:

 firebase_auth: For Firebase authentication

 flutter_secure_storage: Secure credential storage

 oauth2: OAuth 2.0 implementation

 google_sign_in: Google authentication

 appwrite: Backend auth services

Slide 126: Conclusion


Navigation and routing are crucial aspects of building Flutter apps. User
authentication:

 Protects sensitive data


 Maintains app integrity
 Can be implemented via multiple packages
 Requires careful credential handling
 Should be combined with secure navigation flows

Flutter's ecosystem provides flexible solutions for authenticated browsing


tailored to different application needs.

You might also like