플러터로 개발된 앱은 기본적으로 뒤로가기를 누르면 꺼지지 않고 home을 누른것처럼 됩니다. 윈도우에서 탐색기창을 최소화시킨것처럼 그냥 백그라운드에서 돌아가는 것입니다.
음악이라도 재생되면 대번에 알겠지만, 음악이 없다면 뒤로가기를 눌렀을때 꺼진건지 어떤건지 바로 알기가 어렵습니다.
어쨌든 뒤로가기를 1번 누르면 '정말 종료하시겠습니까?'하는 메시지를 띄워주고, 뒤로가기를 바로 1번더 누르면 꺼지는 코드는 아래와 같습니다.
1) 기본 : Toast 기능 사용하기
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DoubleBack(
message:"Press back again to close",
child: Home(),
),
),
}
}
2) 옵션 스타일이 있는 기본값(TOAST 사용)
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DoubleBack(
message:"Press back again to close",
child: Home(),
),
),
// optional style
textStyle: TextStyle(
fontSize: 13,
color: Colors.white,
),
background: Colors.red,
backgroundRadius: 30,
);
}
}
3) 사용자 지정(예: 스낵바 사용) #
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DoubleBack(
onFirstBackPress: (context) {
// you can use your custom here
// change this with your custom action
final snackBar = SnackBar(content: Text('Press back again to exit'));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
// ---
},
child: Home(),
),
);
}
}
4) 사용자 지정 지연 #
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DoubleBack(
onFirstBackPress: (context) {
Flushbar(
title: "Hey User",
message: "Press back again to exit",
duration: Duration(seconds: 15), // show 15 second flushbar
)..show(context);
},
child: Home(),
waitForSecondBackPress: 15, // wait for 15 second for second back pressed
),
);
}
}
5) 사용자 정의 조건 #
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Imagine that you are using materialbottom and only want to close when tabIndex = 0
home: DoubleBack(
condition: tabIndex == 0, // only show message when tabIndex=0
onConditionFail: (){
setState((){
tabIndex = 0; // if not 0, set pageview jumptopage 0
});
}
child: Home(),
),
);
}
}
댓글