본문 바로가기
Mobile/Flutter

[Flutter] 뒤로 가기 두 번 입력 시 앱 종료되게 하기

by C_Meaning 2023. 11. 22.
728x90

 

 

최근 Flutter가 업데이트 되면서 이 전에 사용했던 위젯인 WillPopScope가 Deprecated 되었습니다.

따라서 기능이 이전된 PopScope 위젯에서 백버튼 이벤트가 발생할 시 처리하는 방법에 대해 설명드리겠습니다.

 

아래는 구현 코드입니다.

class _HomePageState extends State<HomePage> {
  DateTime? backPressedTime;
  late FToast fToast;

  @override
  void initState() {
    super.initState();
    fToast = FToast(); //토스트 메시지 초기화
    fToast.init(context);
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: PopScope(
        canPop: false, // 백 버튼 이벤트 true = 항시 받음 / false = 무조건 막음
        onPopInvoked: (bool didPop) {
          DateTime nowTime = DateTime.now();
          if (didPop == false &&
              (backPressedTime == null ||
                  nowTime.difference(backPressedTime!) >
                      Duration(seconds: 2))) {
            backPressedTime = nowTime;
            showToast(fToast, backPressForExit, 2);
          } else {
            SystemNavigator.pop(); //앱 종료
          }
        },
        child: Scaffold(
        
        .......
        ....
        ..
        

//토스트 메시지 메서드
void showToast(FToast fToast, String msg, int duration) {
  Widget toast = Container(
    padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(25.0),
      color: overlayColor,
    ),
    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(Icons.error_outline, size: 30),
        SizedBox(
          width: 12.0,
        ),
        Text(msg),
      ],
    ),
  );

  fToast.showToast(
    child: toast,
    gravity: ToastGravity.BOTTOM,
    toastDuration: Duration(seconds: duration),
  );
}

 

PopScope 위젯의 사용 방법은 간단합니다.

canPop 속성 파라미터에는 bool 값을 받아 백버튼 이벤트를 제어합니다.

onPopInvoked 속성은 canPop의 값이 false 상태일 때만 사용 가능한 속성이며 false 상태일 때 이벤트가 들어오면 실행되는 콜백함수입니다.

 

사용한 토스트 메시지 패키지는 여기에서 인스톨하여 사용하시면 됩니다.

 

fluttertoast | Flutter Package

Toast Library for Flutter, Easily create toast messages in single line of code

pub.dev

 

728x90

댓글