import 'package:flutter/material.dart';
import 'package:get/get.dart';

class IXBackButtonDispatcher extends BackButtonDispatcher
    with WidgetsBindingObserver {
  /// Create a root back button dispatcher.
  IXBackButtonDispatcher();

  @override
  void addCallback(ValueGetter<Future<bool>> callback) {
    if (!hasCallbacks) {
      WidgetsBinding.instance.addObserver(this);
    }
    super.addCallback(callback);
  }

  @override
  void removeCallback(ValueGetter<Future<bool>> callback) {
    super.removeCallback(callback);
    if (!hasCallbacks) {
      WidgetsBinding.instance.removeObserver(this);
    }
  }

  @override
  Future<bool> didPopRoute() async {
    final maybePop = await Get.rawRoute?.navigator?.maybePop();
    return maybePop ?? invokeCallback(Future.value(false));
  }
}
