首页 > 解决方案 > 'Future 类型的值' 无法从该方法返回,因为它的返回类型为 'Future

问题描述

Future<bool> foo(BuildContext context) {
  return Navigator.pushNamed<bool>(context, '/bar'); // Error
}

错误:

无法从函数“foo”返回“Future<bool?>”类型的值,因为它的返回类型为“Future”

标签: flutterdartdart-null-safety

解决方案


Navigator.push无法返回不可为空的类型,因为在您的/bar路由中,您可能会执行以下操作,而无需在结果参数中传递任何值。

Navigator.pop(context);

您应该将签名从更改Future<bool>Future<bool?>

Future<bool?> foo(BuildContext context) {
  return Navigator.pushNamed<bool>(context, '/bar');
}

推荐阅读