seong

Flutter - 뒤로가기 버튼 클릭시 앱 종료 본문

Flutter/Flutter

Flutter - 뒤로가기 버튼 클릭시 앱 종료

hyeonseong 2023. 12. 3. 14:22

사용자가 뒤로가기를 실수로 눌러 종료됨을 방지 하기 위해 두번 클릭시 종료되게 만들어주었다.

1. Scaffold위젯을 WillpopScope위젯으로 감싸준다

WillPopScope(
	onWillPop: onWillPop(),
    child: Scaffold(),
    );

2. onWillpop 함수 작성 : 뒤로가기 버튼 클릭시 실행되는 함수이다.

DateTime? backPressTime;

Future<bool> onWillPop() async {
	// 현재시간 
    DateTime now = DateTime.now();
    if (backPressTime == null ||
        now.difference(backPressTime!) > const Duration(seconds: 2)) {
      backPressTime = now;
      // Toast팝업 띄워준다.
      Fluttertoast.showToast(msg: localization.closeButton);
      //AOS의 앱 종료 - SystemChannel.pop
      return await SystemChannels.platform.invokeMethod('SystemChannel.pop');
    }
    //onWillPop의 type는 Future타입이기 때문에 Future.value 리턴
    return Future.value(true);
  }