Flutter WillPopScope 和 AlertDialog 迁移到空安全

时间:2021-04-20 18:37:33

标签: flutter dart-null-safety

我最近将我的 Flutter 应用程序迁移到了 null-safety,但 WillPopScope 与 AlertDialog 结合使用会导致问题。 function showMovies(movies) { main.innerHTML = ""; movies.forEach((movie) => { const { title, poster_path, vote_average, overview } = movie; const movieEl = document.createElement("div"); movieEl.classList.add("movie"); movieEl.innerHTML = ` <img src="${IMG_PATH + poster_path}" alt="${title}" /> <div class="movie-info"> <h3>${title}</h3> <span class="${getClassByRate(vote_average)}">${vote_average}</span> </div> <div class="overview"> <h3>Overview</h3> ${overview} </div> `; main.appendChild(movieEl); }); } 期望 WillPopScopeFuture<bool> 返回 showDialog,我不知道如何将一个投射到另一个上。

Future<bool?>

本示例中所示的 onWillPop 中的强制转换 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; } } 不起作用。

(() => _onBackPressed(context)) as Future<bool> Function()

知道如何捕获 showDialog 返回的空值并使 willPopScope 再次开心吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我想最简单的是:

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