Flutter Tutorial:
Flutter Widgets:
Flutter Advance
Flutter REST API
Advanced Concepts
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips:
Interview Questions
Flutter 100 Interview Questions
Navigator Observer
NavigatorObserver is a one the Flutter framework class that allows to observe changes in the navigation stack. It works for observing events related to navigation stack.
In simple language, NavigatorObserver is a class that listens to navigation events such as when a new route is pushed, popped, or replaced onto the navigation stack. It is used to perform various tasks like analytics tracking, logging, or even updating UI components when a navigation event occurs.
The NavigatorObserver is abstract class in Flutter Framework and defines a set of methods.
didPush(route, previousRoute): This method is called when a new route is pushed onto the navigation stack.
didPop(route, previousRoute): This method is called when a route is popped off the navigation stack.
didRemove(route, previousRoute): This method is called when a route is removed from the navigation stack.
didReplace(newRoute, oldRoute): This method is called when a route is replaced by another route.
To use NavigatorObserver in your app, we need to create a class that extends NavigatorObserver and implement the necessary functions.
import 'package:flutter/material.dart';
class MyObserver extends NavigatorObserver {
//This method push to new screen/page
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
print('New route pushed: ${route.settings.name}');
}
//This method move back to previous page
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
print('Route popped: ${route.settings.name}');
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('My App')),
body: Center(
child: Text('Hello World!'),
),
),
navigatorObservers: [MyObserver()], // Here we use navigatorObservers
));
}
In the above example, MyObserver that extends NavigatorObserver. We then override the didPush and didPop methods to print a message to the console whenever a new route is pushed onto the stack, or when a route is popped off the stack.
NavigatorObserver class provides a powerful way to customize the behavior of the Navigator widget in your Flutter app, and to respond to changes in the navigation stack in a flexible and customized way.