【发布时间】:2020-10-07 20:18:00
【问题描述】:
我有一个 AlertDialog 会在转到新屏幕时立即出现。它有 BACK 和 GO 按钮。仅当用户按下 GO 时,我才需要在关闭 AlertDialog 时留在此屏幕中。如果用户按下 BACK 按钮或 BACK Android 按钮,我需要转到上一个屏幕,而不是留在当前屏幕。 当我关闭 AlertDialog 时,我在 OK 的情况下使用 Navigator.pop(context, false),在 BACK 的情况下使用 Navigator.pop(context, true) 如果这是真的,则使用 bool 返回类型作为第二个 Navigator.pop(context)到上一个屏幕。
@override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback(
(_) => _showDialog().then((isScreenToPop) {
//ERROR: Unhandled Exception: Failed assertion: boolean expression must not be null
if (isScreenToPop) {
Navigator.pop(context);
} else {
setState(() {});
}
}),
);
}
现在我需要检测对 BACK Android 按钮的点击。为此,我将 WillPopScope 与 Future.value(true) 一起使用,但返回 null 并且使用第二个 Navigator.pop(context) 的评估返回 Unhandled Exception: Failed assertion: boolean expression must not be null。
Future<bool> _showADialog() {
return showDialog(
context: context,
barrierDismissible: false,
builder: (_) {
return WillPopScope(
onWillPop: () async {
//THIS RETURN NULL AND NOT Future<true>
return Future.value(true);
},
child: StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
actions: <Widget>[
FlatButton(
child: Text('BACK'),
onPressed: () {
Navigator.pop<bool>(context, true);
},
),
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.pop<bool>(context, false);
},
),
],
);
},
),
);
},
);
}
暂时的解决方案如下,但我不喜欢。
if (isScreenToPop == null || isScreenToPop) {
Navigator.pop(context);
} else {
setState(() {});
}
【问题讨论】: