Routes and Navigator in Flutter
Flutter is an open-source mobile app SDK created by Google. Flutter uses Dart language for creating mobile apps, that follow object-oriented concepts. Flutter has a very good reach among mobile app developers because of its striking features like cross-platform development, hot reload, hot restart, eye-catching UI, etc. In flutter, from text to padding, everything is a widget. Everything in Flutter is a widget.
Route: Apps are the new trend. The number of apps available in the play Store nowadays is quite a lot. The apps display their content in a full-screen container called pages or screens. In flutter, the pages or screens are called Routes. In android, these pages/screens are referred to as Activity and in iOS, it is referred to as ViewController. But, in a flutter, routes are referred to as Widgets. In Flutter, a Page / Screen is called a Route.
Creating routes: A route can be written in the form of a “Class” in Dart using object-oriented concepts. Each route can be written as a separate class and has its own contents and UI.
Now let’s create two routes, each having unique App Bars and Raised Buttons. The code is as follows:
Navigator: As the name suggests, Navigator is a widget that helps us to navigate between the routes. The navigator follows stack method when dealing with the routes. Based on the actions made by the user, the routes are stacked one over the other and when pressed back, it goes to the most recently visited route. Navigator is a widget that follows a stack discipline.
Defining Home: While navigating, the first thing that we need to do is to define or initialize the “home page”. The home page can be any route according to our needs. The home usually will be placed at the bottom of the navigator stack. Now let’s see how to initialize our HomeRoute() as our home page:
Navigating to a Page: Since we have defined our Home, all the remaining is to navigate from home to another route of the app. For that the navigator widget has a method called Navigator.push(). This method pushes the route on top of the home, thereby displaying the second route. The code for pushing a route into the stack is as follows:
Navigating Back to Home: Now we have arrived at our destination, but how do we go back home? For that, the navigator has a method called Navigator.pop(). This helps us to remove the present route from the stack so that we go back to our home route. This can be done as follows:
Example: So, this is how we can navigate between two pages in an app. The whole code for the above flutter app is as follows: