当一个界面中有WillPopScope组件时,在页面返回时会触发回调,决定是否返回。可用于二次确认退出的场景。

WillPopScope使用

  1. <br />【child】 : 子组件 【Widget】<br />【onWillPop】 : 返回回调 【WillPopCallback】<br />![75.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589444794889-6813ea18-12b3-4f33-8299-6e979d6873b6.gif#align=left&display=inline&height=209&margin=%5Bobject%20Object%5D&name=75.gif&originHeight=209&originWidth=387&size=245477&status=done&style=none&width=387)
  1. import 'package:flutter/material.dart';
  2. class CustomWillPopScope extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return Container(
  6. child: WillPopScope(child: (BackButton()),
  7. onWillPop: ()=>_willPop(context)),
  8. );
  9. }
  10. Future<bool> _willPop(context) async{
  11. return await showDialog(
  12. context: context,
  13. builder: (context) => AlertDialog(
  14. shape: RoundedRectangleBorder(
  15. borderRadius: BorderRadius.all(Radius.circular(10))),
  16. title: Text('提示'),
  17. content: Text('你确定要离开此页吗?'),
  18. actions: <Widget>[
  19. FlatButton(
  20. onPressed: () => Navigator.of(context).pop(true),
  21. child: Text('确定'),
  22. ),
  23. FlatButton(
  24. onPressed: () => Navigator.of(context).pop(false),
  25. child: Text('取消'),
  26. ),
  27. ],
  28. ),
  29. ) ?? false;
  30. }
  31. }