我创建了一个屏幕
DashBoard
,因为我设置了底部导航并设置了所有工作的其他屏幕,但我需要添加功能,当用户按后退按钮而不是选择其他选项卡时,它会导航到第一个选项卡,否则打开警报对话框用于询问诸如 “您确定要退出该应用程序吗?”.
我已经使用在仪表板屏幕中设置的 Will Pop 范围来实现。这是我的代码。
class DashBoardView extends GetWidget<DashBoardController> {
const DashBoardView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
MySize().init(context);
getStatusBarColor(color: AppColor.whiteF9F9F9);
return WillPopScope(
child: Scaffold(
body: Obx(() => controller.pages[controller.currentIndex.value]),
bottomNavigationBar: customBottomNavigation(),
),
onWillPop: () {
if (controller.currentIndex.value == 0) {
AppDialog.appAlertDialog(
context: context,
description: "Are you sure you want to exit\nfrom the app? ",
question: 'Exit app',
questionTextStyle: TextStyle(fontSize: 14, color: AppColor.grey, fontWeight: FontWeight.w700),
onTap: () {
Get.put(SocketController()).disconnectFromSocket();
exit(0);
});
} else {
controller.currentIndex.value = 0;
controller.update();
}
return Future.value(false);
});
}
}
但它在 Android 14+ 版本中不起作用,我还按照最新更新将 Will pop 范围替换为 PopScope,但它仍然不起作用。
如果有人遇到这个问题,请给我有关 Android 14+ 版本中此功能的建议。
试试这个-
retrun WillPopScope(
onWillPop: exitPopup,
..... );
Future<bool> exitPopup() async {
return await showDialog(
context: context,
builder: (context) => AlertDialog(
contentPadding: EdgeInsets.zero,
content: Container(
alignment: Alignment.center,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.only(
topRight: Radius.circular(3.0),
// bottomRight: Radius.circular(40.0),
topLeft: Radius.circular(6.0),
// bottomLeft: Radius.circular(40.0),
),
),
height: 40,
child: Text(
"Alert!",
textAlign: TextAlign.center,
style: TextStyle(
color: BrandColors.kRed, fontWeight: FontWeight.bold),
),
),
actions: [
Container(
alignment: Alignment.center,
margin: EdgeInsets.symmetric(vertical: 20),
child: Text(
"Do you want to exit the application?",
style: TextStyle(fontWeight: FontWeight.bold),
)),
Row(
children: [
SizedBox(width: 5),
Expanded(
child: OutlinedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(BrandColors.brandColor),
),
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel',
style: TextStyle(color: Colors.white)),
),
),
SizedBox(width: 5),
Expanded(
child: OutlinedButton(
style: ButtonStyle(
// backgroundColor: MaterialStateProperty.all(
// Colors.blue.withOpacity(0.2)),
),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Yes',
style: TextStyle(color: Colors.black)),
),
),
SizedBox(width: 5),
],
),
// SizedBox(height: 20),
],
),
) ??
false;
}