Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Create routing in flutter

How to create routing in flutter and pass parameters to routes ?

Aman Jain, January 24, 2022October 4, 2022

Flutter has multiple ways to create navigation and routing. In our last article i demonstrate How to navigate between one page to another in flutter and in this article i will show you to create a router where we can define all routes using flutter named routes.

Fluter named routes are used to create and handle navigation between pages. Using named routes we can create a name for path and then we can call it in anywhere in our application to navigate to page.

We will use MaterialApp widget to create the routing. MaterialApp widget accepts routes, initialRoute and builder key as parameter to create the routes and child pages as below

MaterialApp(
        title: 'Named Routes Demo',
        initialRoute: '/',
        routes: {
          '/': (context) =>  const Home(),
          '/Products': (context) => const Products(),
        }

);

here we used onGenerateRoute to pass the parameters between the pages using Navigator and MaterialPageRoute widget.

Let’s understand routing in flutter with example

Step 1 : Create flutter project

Very first step is to create the fluter application using command line tool or in Android studio.

flutter create example_app

This will create a new project with name my_app then go in to the folder.

Step 2 : Create two widgets for navigation

Now, Create two widgets to navigate between the pages. Let’s create one widget name as Home and Second as Products . From home screen we will pass params to it and will access it to another page which is Products.

File : lib/Home.dart

class Home extends StatelessWidget {
   const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text("Home Screen"),
            ElevatedButton(onPressed: (){
              Navigator.pushNamed(context, '/Products',arguments:{"id":1,"name":"apple"});
            }, child: const Text("Navigate to Apple")),

            ElevatedButton(onPressed: (){
              Navigator.pushNamed(context, '/Products',arguments:{"id":2,"name":"Nokia"});
            }, child: const Text("Navigate to Nokia"))
          ],
        ),
      ),
    );
  }
}

Here we used Navigator.push to navigate to another page which is Products and also used Scaffold for material mobile design. As you can see we used arguments to pass the params to another page.

lib/Products.dart

class Products extends StatelessWidget {
  const Products({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    Map arguments = ModalRoute.of(context)?.settings.arguments as Map;

    return  Scaffold(
      appBar: AppBar(
        title:  Text('Product ${arguments['name']}'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
             Text("${arguments['name']} and id ${arguments['id']}"),
            ElevatedButton(onPressed: (){
              Navigator.pop(context);
            }, child: const Text("Navigate back"))
          ],
        ),
      ),
    );
  }
}

We used here Navigator.pop to go back to the last page.

Step 3 : Add Routing widget

Now create routing for these two pages using MaterialApp. As you can see in below example we have created two routes / to access the home screen and /Products to access the products page.

We also create builder using Navigator and in Navigator we implemented onGenerateRoute to create MaterialPageRoute to access the params between pages.

class AppRouter extends StatelessWidget {
  const AppRouter({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Named Routes Demo',

      \\this is optional
        builder: (context, widget) => Navigator(
              onGenerateRoute: (RouteSettings settings) => MaterialPageRoute(
                builder: (ctx) {
                  return Container(
                    child: widget,
                  );
                },
              ),
            ),
  \\this is optional
        initialRoute: '/',
        routes: {
          '/': (context) => const Home(),
          '/Products': (context) => const Products(),
        });
  }
}

Step 4 : Add Page to main file

Simply run the project using command line or in android studio to check the implementation.

import 'package:flutter/material.dart';
import 'package:example_app/AppRouter.dart';
import 'package:example_app/Home.dart';
import 'package:example_app/Products.dart';

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

Step 5: Run the project

Add you new pages to main.dart and start navigating.

flutter run lib/main.dart

How to pass the data between pages using navigator.push?

In the above example we navigate page to another page but not passed any data to other page so to pass the data between one or two page we need to pass extra params to Navigator as below

In page widgets

 Navigator.pushNamed(context, '/Products',arguments:{"id":2,"name":"Nokia"});

and to access the params in another widget

  final String title;
  const SecondPageWidget(this.title,{Key? key}) : super(key: key);

Run the implementation in dartpad.

Related

Dart Flutter Flutterrouting

Post navigation

Previous post
Next post

Related Posts

Dart How to create a scroll view in flutter

How to create a scroll view in flutter ?

January 8, 2022November 5, 2023

Flutter provides multiple way to scroll the view and one of the most efficient way is ListView.builder. Using the ListView class we can configure multiple options. Using these widgets we can create horizontal as well vertical scroll. ListView GridView CustomScrollView DraggableScrollableSheet NestedScrollView PageView SingleChildScrollView Here are the few scroll widgets…

Read More
Dart How to Remove Debug Text Banner in Flutter Application

How to Remove Debug Text Banner in Flutter Application?

September 11, 2022March 16, 2024

In this tutorial we will learn to remove debug text banner in flutter application. When we first time setup the project and install it in device it shows debug text banner at right top side of application so if we want to remove it we simply need to add debugShowCheckedModeBanner…

Read More
Dart How to add one side border to container widget flutter

How to add one side border to container widget flutter?

September 17, 2022March 16, 2024

In this tutorial we will learn to add add one side border to container widget flutter. Border is used to create border around the widget or container and using the border we can style it in different way like adding the width of border, color of border and one side…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version