Navigator的then方法存在语法错误,VSCode提示参数类型问题
我之前也碰到过一模一样的报错,其实这是空安全机制在严格校验类型导致的。先贴出你这段有问题的代码:
_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
相关产品推荐
相关产品推荐

