如何覆盖 Flutter 中的“返回"按钮? [英] How To Override the “Back” button in Flutter?
本文介绍了如何覆盖 Flutter 中的“返回"按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的主页小部件上,当用户点击系统返回按钮时,我想显示一个确认对话框,询问您要退出应用程序吗?"
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
来实现这一点.
You can use WillPopScope
to achieve this.
示例:
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.
The ??-operator
checks for null
, see here. This is important because if you click outside the dialog, showDialog returns null
and in this case false is returned.
希望有帮助!
这篇关于如何覆盖 Flutter 中的“返回"按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文