簡體   English   中英

Flutter WillPopScope 與 AlertDialog 遷移到零安全

[英]Flutter WillPopScope with AlertDialog migration to null-safety

我最近將我的 Flutter 應用程序遷移到空安全,但 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 返回的 null 值並使 willPopScope 再次高興嗎?

我想最簡單的是:

Future<bool> _onBackPressed(BuildContext context) async {
    ...
    return (await showDialog(..)) ?? false // if dialog returns null, return false instead
    ...

或者

bool? dialogResp = await showDialog(...);
if(dialogResp !=) 
   return dialogResp; 
else 
   return false;

或者

Future<bool> _onBackPressed(BuildContext context) async {
    ...
    return showDialog(..).then((x) => x ?? false)
    ...

由於showDialog可以返回null ,我們可以使用?? 運算符在showDialog返回null時返回另一個值。 在這種情況下, false

  Future<bool> _onWillPop() async {
    return (await showDialog(
      context: context,
      builder: (context) => new AlertDialog(),
    )) ?? false;
  }

然后在WillPopScope上使用它:

    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM