【发布时间】:2017-11-21 23:00:03
【问题描述】:
在用户通过按 Android 设备上的Back 按钮离开当前路线之前,我需要显示一个警报对话框。我试图通过在小部件状态下实现WidgetsBindingObserver 来拦截后退按钮的行为。在 GitHub 上有一个关于同一主题的封闭 issue。但是,我的代码无法正常工作,因为从未调用过 didPopRoute() 方法。下面是我的代码:
import 'dart:async';
import 'package:flutter/material.dart';
class NewEntry extends StatefulWidget {
NewEntry({Key key, this.title}) :super(key: key);
final String title;
@override
State<StatefulWidget> createState() => new _NewEntryState();
}
class _NewEntryState extends State<NewEntry> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Future<bool> didPopRoute() {
return showDialog(
context: context,
child: 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(true),
child: new Text('No'),
),
new FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: new Text('Yes'),
),
],
),
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.edit),
onPressed: () {},
),
);
}
}
【问题讨论】: