Navigation Service in flutter

import 'package:flutter/material.dart';

class NavigationService {
  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  void pop(value) {
    return navigatorKey.currentState!.pop(value);
  }

  void goBack() {
    return navigatorKey.currentState!.pop();
  }

  bool canPop() {
    return navigatorKey.currentState!.canPop();
  }

  void checkAndPop() { 
    if(canPop()) { 
      return navigatorKey.currentState!.pop();
    }
  }



  void popUntil(String desiredRoute) {
    return navigatorKey.currentState!.popUntil((route) {
      return route.settings.name == desiredRoute;
    });
  }

  Future pushNamedAndRemoveUntil(route, popToInitial) {
    return navigatorKey.currentState!.pushNamedAndRemoveUntil(
      route,
      (Route<dynamic> route) => popToInitial,
    );
  }



  Future pushReplacementNamed(String desiredRoute, {dynamic arguments}) {
    return navigatorKey.currentState!
        .pushReplacementNamed(desiredRoute, arguments: arguments);
  }

  Future pushNamed(String desiredRoute, {dynamic arguments}) {
    return navigatorKey.currentState!
        .pushNamed(desiredRoute, arguments: arguments);
  }



  NavigatorState? getNavigationState() {
    return navigatorKey.currentState;
  }

  BuildContext getNavigationContext() {
    return navigatorKey.currentState!.context;
  }

  void popDialog(value) {
    return navigatorKey.currentState!.pop(value);
  }
}
Updated on