You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Navigator的then方法存在语法错误,VSCode提示参数类型问题

解决Dart中Navigator.push.then的参数类型不匹配问题

我之前也碰到过一模一样的报错,其实这是空安全机制在严格校验类型导致的。先贴出你这段有问题的代码:

_openEditListingDialog(Listing listing, Function(Listing) onSubmittedCallback) async {
  Navigator
      .of(context)
      .push(
        new MaterialPageRoute<Listing>(
          builder: (BuildContext context) {
            return new ListingDialog.edit(listing);
          },
          fullscreenDialog: true,
        ),
      )
      .then((Listing newEntry) {
        if (newEntry != null) {
          newEntry.id = listing.id;
          onSubmittedCallback(newEntry);
        }
      });
}

问题根源

在启用空安全的Dart环境里,Navigator.push<T>返回的是Future<T?>——哪怕你指定了泛型为Listing,用户也可能直接关闭对话框不返回任何数据,所以回调参数必须是可空的Listing?,但你现在写的是(Listing newEntry),这就和Dart预期的参数类型不匹配了。

两种可行的解决办法

方法1:修正回调参数的可空类型

直接给then的回调参数加上可空标记,保留原有代码结构:

Navigator
    .of(context)
    .push(
      new MaterialPageRoute<Listing>(
        builder: (BuildContext context) {
          return new ListingDialog.edit(listing);
        },
        fullscreenDialog: true,
      ),
    )
    .then((Listing? newEntry) { // 这里添加?标记参数为可空类型
      if (newEntry != null) {
        newEntry.id = listing.id;
        onSubmittedCallback(newEntry);
      }
    });

方法2:改用async/await(更推荐)

既然你的方法已经标记了async,不如直接用await改写代码,逻辑更直观,也符合Dart的现代写法:

_openEditListingDialog(Listing listing, Function(Listing) onSubmittedCallback) async {
  final Listing? newEntry = await Navigator.of(context).push<Listing>(
    MaterialPageRoute<Listing>(
      builder: (BuildContext context) {
        return ListingDialog.edit(listing);
      },
      fullscreenDialog: true,
    ),
  );

  if (newEntry != null) {
    newEntry.id = listing.id;
    onSubmittedCallback(newEntry);
  }
}

两种方法都能解决VS Code的类型报错,代码也能正常运行。

内容的提问来源于stack exchange,提问作者Igor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:59:54