Multi Page Applications in Flutter
Apps are widely used by humans in this techie world. The number of apps in the app store is increasing day by day. Due to this competition, app developers have started to add a number of features to their apps. To reduce this complexity, the content of the app is mostly divided into various pages so that the user can navigate between these pages with ease.
Flutter is an open-source mobile app SDK, that is used to develop cross-platform mobile applications. Flutter is becoming popular these years because of its stunning features like hot reload, attractive UIs, etc. In Flutter, everything is a Widget.
Routes and Navigators: In Flutter, pages/screens are called Routes. The process of navigating from one route to another is performed by a widget called the Navigator. The navigator maintains all its child routes in the form of stacks. It has many methods like push() and pop() which works under stack discipline. But, for multi-page applications, we are going to use a unique method called the pushNamed(). This method mainly follows object-oriented concepts.
The Navigator.pushNamed() method is used to call a route, whose class has been created and defined beforehand. It is just like calling a class when needed in OOPs. Now, let us move on to creating our Multi-Page Application.
Creating a Route: Routes are mainly created in the form of classes. Each route has a unique class with unique contents and UI in them. Here, we are going to create three routes namely, HomeRoute(), SecondRoute() and ThirdRoute(). Each route will have an App bar containing a unique title and a raised button for navigating between the routes. A route can be created as follows:
Defining the Routes: Before navigating between routes, it is highly essential to define them in the MaterialApp widget. This helps us to access and call them as easily as possible. Since we are initializing the first route, it is not necessary for us to mention the home route. The routes can be defined as follows:
From the code, it is understood that each route has been named uniquely. So, when the navigator widget encounters any of these names in the route class then it navigates to the respective route. The initialRoute in this code specifies the starting route of the app and it is symbolized by ‘/’ symbol. It is a mandatory thing to initialize the home page in this widget.
Navigating to a Page: The Navigator.pushNamed() method comes into play in this segment. This method calls the name of a particular route in a route class. Thereby, initializing the navigation process. The navigation can be done as follows:
Navigating back: But, when it comes to visiting the most recent route visited, Navigator.pop() method can be used. It helps us to navigate back to the last route. In this case, the stack discipline is as followed. The pop method is used as follows:
So, now let’s see how it’s all these codes have been combined to create this Multi-Page Application.