【发布时间】:2021-07-14 23:31:56
【问题描述】:
我最近将我的 Flutter 应用程序迁移到了 null-safety,但 WillPopScope 与 AlertDialog 结合使用会导致问题。 WillPopScope 期望 Future<bool> 但 showDialog 返回 Future<bool?> 我不知道如何将一个投射到另一个上。
Widget _buildBody(BuildContext context) {
return WillPopScope(
onWillPop: (() => _onBackPressed(context)) as Future<bool> Function(),
child: new Container([...]),
);
}
// this should return a Future<bool> but showDialog doesn't allow that
Future<bool?> _onBackPressed(BuildContext context) async {
if (someCondition) {
// showDialog returns a Future<T?>
return showDialog(
context: context,
builder: (context) => new AlertDialog(
[...]
actions: <Widget>[
new TextButton(
child: Text("cancel",
onPressed: () => Navigator.of(context).pop(false),
),
new TextButton(
child: Text("discard",
onPressed: () => Navigator.of(context).pop(true),
),
],
));
} else {
return true;
}
}
此示例中显示的 onWillPop 中的演员 (() => _onBackPressed(context)) as Future<bool> Function() 不起作用。
The following _CastError was thrown building Builder(dirty):
type '() => Future<bool?>' is not a subtype of type '() => Future<bool>' in type cast
知道如何捕获 showDialog 返回的空值并让 willPopScope 再次高兴吗?
【问题讨论】: