当一个界面中有WillPopScope组件时,在页面返回时会触发回调,决定是否返回。可用于二次确认退出的场景。
WillPopScope使用
<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)
import 'package:flutter/material.dart';
class CustomWillPopScope extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: WillPopScope(child: (BackButton()),
onWillPop: ()=>_willPop(context)),
);
}
Future<bool> _willPop(context) async{
return await showDialog(
context: context,
builder: (context) => AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10))),
title: Text('提示'),
content: Text('你确定要离开此页吗?'),
actions: <Widget>[
FlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('确定'),
),
FlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text('取消'),
),
],
),
) ?? false;
}
}