这是实现目标的完整示例。 WillPopScope 需要maybePop 调用才能执行您的逻辑:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: RaisedButton(
child: Text('Jump To Next Screen'),
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => ModalScreen())),
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class ModalScreen extends StatefulWidget {
@override
_ModalScreenState createState() => _ModalScreenState();
}
class _ModalScreenState extends State<ModalScreen> {
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
appBar: AppBar(
leading: InkResponse(
child: Icon(Icons.arrow_back),
onTap: () => Navigator.of(context).maybePop(),
),
),
backgroundColor: Colors.blue,
body: Center(
child: RaisedButton(
child: Text('Let\'s go back'),
onPressed: () {
Navigator.of(context).maybePop();
},
),
),
),
onWillPop: () => _willPop(context),
);
}
Future<bool> _willPop(BuildContext context) {
final completer = Completer<bool>();
showModalBottomSheet(
context: context,
builder: (buildContext) {
return SizedBox(
height: 200,
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Text('Are you sure?'),
),
MaterialButton(
child: Text('YES'),
onPressed: () {
completer.complete(true);
Navigator.of(context).pop();
}),
MaterialButton(
child: Text('NO'),
onPressed: () {
completer.complete(true);
}),
],
),
);
});
return completer.future;
}
}
一旦您为您的模态框返回true,您还需要弹出屏幕,因为模态框有自己的上下文需要被弹出。
最终结果如下: