在我的Home小部件上,当用户点击系统后退按钮时,我想显示一个确认对话框,询问“你想退出应用程序吗?”
我不明白我应该如何覆盖或处理系统后退按钮。
答案 0 :(得分:65)
您可以使用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() {
return 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>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('No'),
),
new FlatButton(
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"),
),
),
);
}
}
希望它有所帮助!