[Flutter]플러터 토스트를 이용한 뒤로 버튼 두번 눌러야 종료(꿀팁)

오늘도 알고보자·2022년 2월 17일
0

Toast를 이용한 뒤로 두번 눌렀을때 종료

요즘 많은 메인에서 뒤로 두번을 눌러야 종료되는 경우가 많다.
그리고 토스트 메세지가 뜨며 이루어진다. Flutter에서 하는 방법을 알고보자.

Toast 설치

Pubspec.yaml에 Toast를 추가해주고 Pub get 해준다.

코드 작성

개인프로젝트가 clean architecture 형태로 작성하다 보니 비즈니스 로직과 UI로직이 따로 되어있다.
나같은 경우에는 util폴더를 따로만들어 그안에 토스트에 대한 로직을 만들었다.

DateTime? currentBackPressTime;

onWillPop() {
  DateTime now = DateTime.now();
  if (currentBackPressTime == null ||
      now.difference(currentBackPressTime!) > const Duration(seconds: 2)) {
    currentBackPressTime = now;
    Fluttertoast.showToast(
        msg: "'뒤로' 버튼을 한번 더 누르시면 종료됩니다.",
        gravity: ToastGravity.BOTTOM,
        backgroundColor: const Color(0xff6E6E6E),
        fontSize: 20,
        toastLength: Toast.LENGTH_SHORT);
    return false;
  }
  return true;
}

몇가지 살펴보면

  • if (currentBackPressTime == null ||
    now.difference(currentBackPressTime!) > const Duration(seconds: 2)) {
    currentBackPressTime = now;

다트에서 DateTime.now를 now로 선언하고
difference 메소드를 사용해 차이 시간을 구해준다.
2초안에 뒤로가기 두번을 누른지 않으면 false로 Toast 메세지가 나오게된다.

  • WillScope는 Scaffold를 감싸고있어야한다.
WillPopScope(
        onWillPop: () async {
          bool result = onWillPop();
          return await Future.value(result);
        },
        child: Scaffold(

Future.value()
지정한 결과값을 가진 future 를 생성하는 constructor 이다.
만들어놓은 onWillPop() 을 result에 담아주고 Future.value()에 result를 담아준다.

그럼 완성!

0개의 댓글