Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Subscribe for Flutter NavigatorRouter Events

How to Subscribe for Flutter Navigator/Router Events ?

Aman Jain, April 29, 2022September 11, 2022

Navigator is used to navigate between the pages and sometimes we want to subscribe for flutter Navigator/Router Events to update the widget state or to perform the specific task during the push and pop of page. Flutter provider RouteObserver mixin to subscribe the events of navigator by which we can perform our task on push and pop.

RouteAware is an interface for objects that know about their present in route. let’s understand 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 a class and Add RouteObserver

Create a simple class named as Helper so that we can use it across multiple files

import 'package:flutter/material.dart';

class Helper  {
 static final RouteObserver<PageRoute> _routeObserver = RouteObserver();
}

Step 3 : Create two widgets for navigation

Now, Create two widgets to navigate between the pages. Let’s create one widget name as HomePage 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/HomePage.dart


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> with RouteAware {

  @override
  void didPush() {
    print('HomePage: Called didPush');
    super.didPush();
  }

  @override
  void didPop() {
    print('HomePage: Called didPop');
    super.didPop();
  }

  @override
  void didPopNext() {
    print('HomePage: Called didPopNext');
    super.didPopNext();
  }

  @override
  void didPushNext() {
    print('HomePage: Called didPushNext');
    super.didPushNext();
  }
  @override
  void initState() {
  WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
    Helper.routeObserver.subscribe(this, ModalRoute.of(context)!);
  });
  super.initState();
 }
  
  @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.

we added

 @override
  void initState() {
  WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
    Helper.routeObserver.subscribe(this, ModalRoute.of(context)!);
  });
  super.initState();
 }

and methods

  1.  didPop(): Called when we call pop method of navigator.
  2. didPopNext(): In this method, on the off chance that you have extended HomePage with RouteAware, and in case SecondPage is popped so HomePage is noticeable now, didPopNext is called.
  3. didPush(): called when the current screen or route has been pushed into the navigation stack.
  4. didPushNext(): called when a new screen/route is pushed from the current screen and the current screen is no longer visible.

and 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.

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Named Routes Demo',
        navigatorObservers: [Helper.routeObserver],
        initialRoute: '/',
        routes: {
          '/': (context) => const HomePage(),
          '/Products': (context) => const Products(),
        });
  }
}

Here we added navigatorObservers: [Helper.routeObserver] for subscribe the events of navigator in widget.

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/HomePage.dart';
import 'package:example_app/Products.dart';

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

Check the implementation here and you can check the console for logs

Share this:

  • Facebook
  • X

Related

Dart Flutter eventsFlutterrouter

Post navigation

Previous post
Next post

Related Posts

Flutter Create a bottom tab in flutter

How to create bottom tab bar in flutter ?

January 9, 2022January 15, 2022

In this tutorial i will show you to create bottom tab in flutter. Now days bottom tabbing is much popular then creating drawer because tabbing is much easy to user and you can easily switch between the tabs. I will show you in this article to change the color of…

Share this:

  • Facebook
  • X
Read More
Flutter How to Use Hash Hexadecimal Color Code in flutter

How to Use Hash Hexadecimal Color Code in flutter ?

September 13, 2022September 13, 2022

Flutter provides color class to use only integer value and RGB value but to use hash hexadecimal color code in flutter we need to add extra efforts so that we can use hash based hexadecimal string in flutter. Hexadecimal colors are those colors which starts with # char. Flutter Color…

Share this:

  • Facebook
  • X
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, 2022November 8, 2023

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…

Share this:

  • Facebook
  • X
Read More

Leave a ReplyCancel reply

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 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • 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

  • How to Call Controller Method from Another Controller in Laravel ?
  • How to Get Domain Name in Laravel ?
  • How to Append Query String to Route in Laravel ?
  • How to Append URL Query Params to Pagination Laravel ?
  • How to Get Today Records in Laravel ?
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version