I have recently migrated my Flutter app to null-safety but WillPopScope in combination with AlertDialog causes a problem. WillPopScope
expects Future<bool>
but showDialog
returns Future<bool?>
and I can't figure out how to cast one onto the other.
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;
}
}
The cast (() => _onBackPressed(context)) as Future<bool> Function()
in onWillPop as shown in this sample is not working.
The following _CastError was thrown building Builder(dirty):
type '() => Future<bool?>' is not a subtype of type '() => Future<bool>' in type cast
Any idea how I can catch the null value returned by showDialog and make willPopScope happy again?