【问题标题】:Flutter WillPopScope with AlertDialog migration to null-safetyFlutter WillPopScope 与 AlertDialog 迁移到空安全
【发布时间】: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 中的演员 (() =&gt; _onBackPressed(context)) as Future&lt;bool&gt; 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 再次高兴吗?

【问题讨论】:

    标签: flutter dart-null-safety


    【解决方案1】:

    我想最简单的方法是:

    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)
        ...
    

    【讨论】:

      【解决方案2】:

      由于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(
      

      【讨论】:

      • 我希望我可以将多个答案标记为正确。感谢您的超级快速和乐于助人的回复,尽管 Nuts 以 1 分钟的优势击败了您!!!
      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 2022-01-23
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 2021-09-04
      • 1970-01-01
      相关资源
      最近更新 更多