반응형
질문
On my Home widget, when user taps system back button, I want to show a confirmation dialog asking "Do you want to exit the App?"
I don't understand how I should override or handle the system back button.
답변
WillPopScope
을(를) 사용하여 이를 달성할 수 있습니다.
예시:
import 'dart:async';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) :super(key: key);
final String title;
@override
State<StatefulWidget> createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<bool> _onWillPop() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: new Text('Yes'),
),
],
),
)) ?? false;
}
@override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: _onWillPop,
child: new Scaffold(
appBar: new AppBar(
title: new Text("Home Page"),
),
body: new Center(
child: new Text("Home Page"),
),
),
);
}
}
??-operator
는 null
을 확인합니다. 여기를 참조하십시오. 이것은 showDialog가 대화 상자 외부를 클릭하면 null
을 반환하므로 이 경우 false가 반환되기 때문에 중요합니다.
반응형
댓글