handleBackPress static method

Future<bool> handleBackPress({
  1. required BuildContext context,
  2. required int currentIndex,
  3. required List<NavBarScreenModel> pages,
  4. Future<bool> globalOnWillPop()?,
  5. bool switchToFirstTabOnBack = true,
  6. bool doubleBackToExit = false,
  7. Duration exitTimeout = const Duration(seconds: 2),
  8. String? exitMessage,
})

Main back handler for BottomNavScaffold

Implementation

static Future<bool> handleBackPress({
  required BuildContext context,
  required int currentIndex,
  required List<NavBarScreenModel> pages,
  Future<bool> Function()? globalOnWillPop,
  bool switchToFirstTabOnBack = true,
  bool doubleBackToExit = false,
  Duration exitTimeout = const Duration(seconds: 2),
  String? exitMessage,
}) async {
  final page = pages[currentIndex];

  // 1. Page-level handler
  if (page.onWillPop != null) {
    final allow = await page.onWillPop!();
    return allow;
  }

  // 2. Global handler
  if (globalOnWillPop != null) {
    final allow = await globalOnWillPop();
    return allow;
  }

  // 3. Nested navigator
  if (page.hasNestedNavigator) {
    final currentNavigator = page.navigatorKey!.currentState;
    if (currentNavigator != null && currentNavigator.canPop()) {
      currentNavigator.pop();
      return false; // handled
    }
  }

  // 4. Switch to first tab
  if (switchToFirstTabOnBack && currentIndex != 0) {
    context.read<BottomNavBarCubit>().updateIndex(0);
    return false; // handled
  }

  // 5. Double back to exit
  if (doubleBackToExit) {
    final allow =
        await checkDoubleBackExit(context, exitTimeout, exitMessage);
    if (!allow) return false; // wait for second back press
  }

  // 6. Default → exit app
  return true;
}