flutter - 手机的后退按钮无法正常工作
问题描述
当我单击后退按钮时,在我的 Flutter 应用程序中关闭。我使用了 onWillpopscope() 但它对我不起作用。我在下面分享我的代码。但是当我创建一个示例项目时,它正在工作。谁能解释一下为什么它在现有应用程序中不起作用。谁能建议我如何实现这一目标。
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> _onBackPressed() {
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 GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child: roundedButton("No", const Color(0xFF167F67),
const Color(0xFFFFFFFF)),
),
new GestureDetector(
onTap: () => Navigator.of(context).pop(true),
child: roundedButton(" Yes ", const Color(0xFF167F67),
const Color(0xFFFFFFFF)),
),
],
),
) ??
false;
}
Widget roundedButton(String buttonLabel, Color bgColor, Color textColor) {
var loginBtn = new Container(
padding: EdgeInsets.all(5.0),
alignment: FractionalOffset.center,
decoration: new BoxDecoration(
color: bgColor,
borderRadius: new BorderRadius.all(const Radius.circular(10.0)),
boxShadow: <BoxShadow>[
BoxShadow(
color: const Color(0xFF696969),
offset: Offset(1.0, 6.0),
blurRadius: 0.001,
),
],
),
child: Text(
buttonLabel,
style: new TextStyle(
color: textColor, fontSize: 20.0, fontWeight: FontWeight.bold),
),
);
return loginBtn;
}
@override
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: _onBackPressed,
child: new Scaffold(
appBar: new AppBar(
title: new Text(
"On Back pressed",
style: new TextStyle(color: Colors.white),
),
),
body: new Center(
child: new Text("Home Page"),
),
),
);
}
}
在 Pubspec 中:
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
解决方案
像这样更改因为child
已弃用,请使用builder
Future<bool> _onWillPop() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Unsaved data will be lost.'),
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;
}
推荐阅读
- php - PHP中的会话变量没有出现
- automation - 对命令“gcloud compute instance-templates delete”自动回答是
- python - 如何从一个 csv 文件中读取多个矩阵?
- javascript - 获取 ENOENT:没有这样的文件或目录,打开...尝试将 App.js/index.js 文件移动到 /src 文件夹中的子文件夹时出错
- android - 如何仅在反应原生的底部设置高程阴影?
- linux - Linux Monodevelop 中的选项卡控件是否有问题?
- docker - 如何从外部 IP 访问容器?
- vba - 如何查找和替换Word的内容?
- python - PCA 对模型性能的影响是什么?
- javascript - 有人可以分解这段代码(解释),因为我对 javascript 不是很好吗?