Flutter
Flutter - onBackPressed(WillPopScope)
대기만성 개발자
2020. 8. 3. 16:04
반응형
소프트웨어 키중 back key를 사용했을때 특별한 처리를 하기 위해서는
onBackPressed가 필요합니다 Native Android에서는 onBackPressed가 이미 있어서
그대로 사용하면 되었지만 Flutter에서는 다른 방법을 통해 해결해야 됩니다
이 방법에 대해서 알아보겠습니다
1. WillPopScope를 이용하여 onBackPressed이벤트 확인
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
await _onBackPressed(context);
return false;
},
child: Scaffold(...)
2. onBackPressed구현
Future<void> _onBackPressed(BuildContext context) async {
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Do you want to exit?'),
actions: <Widget>[
TextButton(
child: const Text('No'),
onPressed: () => Navigator.pop(context),
),
TextButton(
child: const Text('Yes'),
onPressed: () => SystemNavigator.pop(),
),
],
),
);
}
AlertDialog는 다른것으로 대체 가능합니다
ex) 바로 종료, 두번 입력시 종료
* 추가로 nullsafety 버전에서는 onWillPop 콜백의 return 값이 Future<bool> 입니다
고로 간단하게 backKey를 금지하는방향으로 설정하려면
onWillPop: () async {
return false;
},
형태로 사용하시면 되겠습니다
반응형