
开篇寄语
Flutter在页面跳转后会在左上方出现一个返回按钮,点击它就会返回到上一页面,其实这个按钮还可以设置触发事件,实现很多有意思的功能,比如如封面图所示,出现弹出框,点击确定后才返回上一页,点击取消则留在这一页,那么该如何实现呢?请看本篇文章。
前情提要
内容详情
以下内容大多是更改lib下的main.dart文件内容,删掉里面的内容,复制粘贴代码,开启调试就可以出现了。
实现页面返回触发命令,涉及到flutter一个组件,名称为——WillPopScope,详情可以参考flutter.dev官网开发文档的介绍,具体用法可以参考下面这个例子:
// main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => OtherScreen()));
},
child: Text('Navigate to OtherScreen'),
),
),
);
}
}
class OtherScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
bool willLeave = false;
// show the confirm dialog
await showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Are you sure want to leave?'),
actions: [
ElevatedButton(
onPressed: () {
willLeave = true;
Navigator.of(context).pop();
},
child: Text('Yes')),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('No'))
],
));
return willLeave;
},
child: Scaffold(
appBar: AppBar(
title: Text('Other Screen'),
),
body: Center(),
));
}
}
实现的效果就如封面图所示的类似了,该效果也加载在了伯衡君最近正在开发的一款App内——Flutter Dictioanry,具体可以参看下面这篇文章:
- 我的微信
- 微信扫一扫加好友
-
- 我的微信公众号
- 扫描关注公众号
-





