패키지, 저장소 및 앱 카테고리 검색

패키지 상세v8.0.5

back_button_interceptor

뒤로 가기 버튼 인터셉터. Android 뒤로 가기 버튼이 눌렸을 때 작업을 수행하는 데 사용할 수 있으며, WillPopScope의 대안으로 활용할 수 있습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
33.8만
좋아요
411
Pub 점수
150

패키지 설치

flutter pub add back_button_interceptor

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

back_button_interceptor 패키지는 안드로이드 뒤로 가기 버튼을 가로채고 앱이 뒤로 이동하기 전에 사용자 정의 로직을 실행할 수 있는 방법을 제공합니다. WillPopScope의 대안으로서, 안드로이드, iOS, 웹, macOS, Windows, Linux에서 플러터 앱의 네비게이션 처리에 더 큰 유연성을 제공합니다. 사용자가 뒤로 가기 버튼을 누를 때 확인 대화상자를 표시하거나 데이터를 저장하거나 복잡한 네비게이션 흐름을 관리하는 데 특히 유용합니다.

사용 사례

  • 모바일 앱에서 뒤로 버튼 누르기 처리
  • 이동 전 확인 대화 상자 표시
  • 화면을 떠나기 전에 저장되지 않은 데이터를 저장합니다
  • 다중 레벨 탐색 흐름 관리
  • 의도하지 않은 탐색 방지
  • 다양한 플랫폼 간에 뒤로 가기 버튼 동작 맞춤 설정

주요 기능

  • 크로스 플랫폼 지원 (Android, iOS, Web, macOS, Windows, Linux)
  • 뒤로 가기 버튼 이벤트를 가로채는 간단한 API
  • 더 나은 제어를 제공하는 WillPopScope의 대안
  • 중첩된 경로 가로채기 지원
  • 뒤로 가기 탐색 취소를 허용합니다
  • Navigator와 원활하게 작동합니다

적합한 대상

  • 뒤로 버튼 동작에 대해 세밀한 제어가 필요한 개발자
  • 이동 전 확인이 필요한 앱
  • 다중 화면 양식 또는 워즈드
  • 크로스플랫폼 플러터 애플리케이션
  • WillPopScope 제한을 회피하는 팀

고려 사항

  • 추가 상태 관리가 필요할 수 있습니다
  • 간단한 탐색이 충분하다면 필요하지 않음
  • 깊이 중첩된 탐색에서 발생할 수 있는 복잡성
  • 의도치 않은 탐색 차단을 방지하기 위해 신중하게 처리해야 합니다
  • 플랫폼 전용 뒤로 버튼 이벤트에 한정 (모든 기기의 하드웨어 버튼은 아님)

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Pub popularity Pub Version GitHub stars Code Climate issues GitHub closed issues GitHub contributors GitHub repo size GitHub forks PRs Welcome Developed by Marcelo Glasberg Glasberg.dev on pub.dev Platforms

back_button_interceptor

In simple cases, when you need to intercept the Android back-button, you usually add WillPopScope to your widget tree. However, when developing stateful widgets that interact with the back button, it's more convenient to use the BackButtonInterceptor.

You may add interceptor functions to be called when the back button is tapped. These functions may perform some useful work, and then, if any of them return true, the default button process (usually popping a Route) will not be fired.

Android 13

To make it work on Android 13 and up, set this to false in the Android manifest:

android:enableOnBackInvokedCallback="false"

In more detail

All added functions are called, in order. If any function returns true, the combined result is true, and the default button process will NOT be fired. Only if all functions return false (or null), the combined result is false, and the default button process will be fired.

Optionally, you may provide a z-index. Functions with a valid z-index will be called before functions with a null z-index, and functions with larger z-index will be called first. When they have the same z-index, functions added last are called first.

Each function gets the boolean stopDefaultButtonEvent that indicates the current combined result from all the previous functions. So, if some function doesn't want to fire if some other previous function already fired, it can do:

if (stopDefaultButtonEvent) return false;

The same result may be obtained if the optional ifNotYetIntercepted parameter is true. Then the function will only be called if all previous functions returned false (that is, if stopDefaultButtonEvent is false).

Notes
  • After you've finished you MUST remove each function by calling the remove() method. Alternatively, you may also provide a name when adding a function, and then later remove it by calling the removeByName(name) method.

  • If any of your interceptors throw an error, the error message will be printed to the console, but the error thrown will be a general error with not much information. You can change the treatment of errors by changing the static errorProcessing field.

  • Your functions can also process information about routes by using the function's RouteInfo info parameter. To get the current route in the navigator, call info.currentRoute(context). Also, info.routeWhenAdded contains the route that was the current one when the interceptor was added through the BackButtonInterceptor.add() method.

  • You can set up some function so that it only runs when the current route is the same route of when the interceptor was created. To that end, you can use info.ifRouteChanged() method:

    bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {    
      if (info.ifRouteChanged(context)) return false;
      ...
    }    
    

    This means the interceptor function is temporarily disabled while, for example, a dialog is open.

  • You can set up some function so that it only runs in certain routes:

    bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {    
      if (["myRoute1", "myRoute2", "myRoute3"]
         .contains(info.currentRoute(context))) return false;
      ...
    }    
    
  • Both info.routeWhenAdded and info.ifRouteChanged() only work if you passed the context parameter to the BackButtonInterceptor.add() method. Otherwise, info.routeWhenAdded will be null and info.ifRouteChanged() will thrown an error.

  • The current route can also be obtained by using the static method BackButtonInterceptor.getCurrentNavigatorRouteName(context).

  • The interceptor function can return bool or Future<bool>.


Examples

Intercepting
@override
void initState() {
   super.initState();
   BackButtonInterceptor.add(myInterceptor);
}

@override
void dispose() {
   BackButtonInterceptor.remove(myInterceptor);
   super.dispose();
}

bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
   print("BACK BUTTON!"); // Do some stuff.
   return true;
}
Named function and z-index
@override
void initState() {
   super.initState();
   BackButtonInterceptor.add(myInterceptor, zIndex:2, name:"SomeName");
}

@override
void dispose() {
   BackButtonInterceptor.removeByName("SomeName");
   super.dispose();
}

bool myInterceptor(bool stopDefaultButtonEvent, RouteInfo info) {
   print("BACK BUTTON!"); // Do some stuff.
   return true;
}
Runnable Examples
  1. main

    Intercepts the back-button and prints a string to the console.

  2. main

    Intercepts the back-button and prints a string to the console, by using an async interceptor function.

  3. main_complex_example

    The first screen has a button which opens a second screen. The second screen has 3 red squares. By tapping the Android back-button (or the "pop" button) each square turns blue, one by one. Only when all squares are blue, tapping the back-button once more will return to the previous screen. Also, if you click the "Open Dialog" button, the interceptors are disabled while the dialog is open.

  4. main_complex_example_test

    This package is test friendly, and this examples shows how to test the back button.

Testing

For testing purposes, the BackButtonInterceptor.popRoute() method may be called directly, to simulate pressing the back button. The list of all fired functions and their results is
recorded in the BackButtonInterceptor.results static variable.

Note: You may want to add BackButtonInterceptor.removeAll(); to your test's setUp function, so that you remove old interceptors between tests.

Debugging

In complex cases, to make it easier for you to debug your interceptors, you may print them to the console, with their names and z-indexes, by doing:

print(BackButtonInterceptor.describe());

Incompatibilities

This package is currently incompatible with deep links of the GoRouter package.

See also:

  • https://docs.flutter.io/flutter/widgets/WillPopScope-class.html
  • https://stackoverflow.com/questions/45916658/de-activate-system-back-button-in-flutter-app-toddler-navigation

By Marcelo Glasberg

glasberg.dev
github.com/marcglasberg
linkedin.com/in/marcglasberg/
twitter.com/glasbergmarcelo
stackoverflow.com/users/3411681/marcg
medium.com/@marcglasberg

My article in the official Flutter documentation:

The Flutter packages I've authored:

My Medium Articles:

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트