位置参数如何通过DART中的无效安全检查?

发布于 2025-01-29 09:15:16 字数 416 浏览 2 评论 0原文

DART中的以下代码行不有效:

void introduce({String name, int age}) {
  print('My name is $name and I am $age years old.');
}

编译器将抱怨参数的无效安全性。

但是,如果我们切换到位置参数,则编译器突然停止抱怨参数的无效安全性,并且以下是有效的:

void introduce(String name, int age) {
  print('My name is $name and I am $age years old.');
}

The following lines of code aren't valid in Dart:

void introduce({String name, int age}) {
  print('My name is $name and I am $age years old.');
}

The compiler will complain about the null safety of the parameters.

But if we switch to the positioned parameters, the compiler suddenly stops complaining about the null safety of the parameters, and the following becomes valid:

void introduce(String name, int age) {
  print('My name is $name and I am $age years old.');
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怂人 2025-02-05 09:15:16

定位参数本质上是必需的。命名和位置可选参数由呼叫者选择传递,因此它们可能是null。可以通过标记必需的来使其正常可选的命名参数。

void introduce({required String name, required int age}) {
  print('My name is $name and I am $age years old.');
}

Positioned parameters are inherently required. Named and positional optional parameters are optionally passed by the caller and it's therefore possible that they're null. One can make the normally optional named parameters required by marking them required.

void introduce({required String name, required int age}) {
  print('My name is $name and I am $age years old.');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文