什么断言在飞镖?

ven*_*yal 53 dart flutter

我只想知道在 Dart中assert有什么用。我试图自己弄清楚,但我无法做到。如果有人向我解释assert的使用,那就太好了。

Ese*_*met 58

更新:在下面查看有关null-safety添加的内容。

让我们想想这个:

import 'package:meta/meta.dart';

class Product {
  final int id;
  final String name;
  final int price;
  final String size;
  final String image;
  final int weight;

  const Product({
    @required this.id,
    @required this.name,
    @required this.price,
    this.size,
    this.image,
    this.weight,
  }) : assert(id != null && name != null && price != null);
}

Run Code Online (Sandbox Code Playgroud)

我们有产品,他们必须有priceidname。但是我们可以处理其他字段,例如通用图像或空白图像图标等。此外,尺寸和重量也不是必须的。

因此,最后我们必须确保必填字段不能为空,因为它们是强制性的。如果您这样做,您将在开发期间处理空值,而不是在已发布的应用程序上出错。

不要忘记这个(来自docs):

在生产代码中,断言被忽略,断言的参数不被评估。

Null-safety update:由于这是关于assert的主题,因此 Dart 是否存在这一事实null-able根本不会改变任何事情。因为assert这一切都是为了做出断言。

一个简单的例子是:

final text = Text('foo');
assert(text.data == 'foo', 'The text must be foo!');
Run Code Online (Sandbox Code Playgroud)

但是在我们的具体示例中,我们需要进行一些更改。因为id, nameorprice不能为 null 并且语法已更改:

import 'package:meta/meta.dart';

class Product {
  final int id;
  final String name;
  final double price;
  final String? size;
  final String? image;
  final int? weight;

  const Product({
    required this.id,
    required this.name,
    required this.price,
    this.size,
    this.image,
    this.weight,
  }) : assert(id > 0 && name.isNotEmpty && price > 0.0);
}

Run Code Online (Sandbox Code Playgroud)

因为它们是空安全的,所以我们需要在zero-values.

  • 现在检查这个断言的用途(或过去的用途)......我想提一下,在最新的更新中有“空安全”功能。 (3认同)
  • 并感谢您的更新。在生产中它被忽略,对我来说它看起来像是一些验证。生产代码有其他选择吗? (2认同)
  • @EsenMehmet 我知道断言在调试模式下工作,我们使用它们来检查参数和变量的值。问题是,当我在调试模式下使用断言检查变量时,如果该值不满足断言的条件,它会给我一个错误,如果用户在输入中输入错误的值,谁会在生产模式下检查该变量?那么我的应用程序会崩溃吗?我无法弄清楚这一点。 (2认同)

iDe*_*ode 7

这里

在开发过程中,使用断言语句—— assert(condition, optionalMessage); — 如果布尔条件为假,则中断正常执行。

假设您要打开一个必须以"https". 你将如何确认这一点?这是一个例子。

例子:

void openUrl({String url}) {
  assert(url.startsWith('https'), 'The url should start with https');
  
  // We can proceed as we 'https' in the url.
}
Run Code Online (Sandbox Code Playgroud)


ayo*_*bra 7

断言类似于错误因为它用于报告不应该发生的不良状态。不同之处在于断言仅在调试模式下检查。它们在生产模式中被完全忽略

前任:

OverlayEntry({
  @required this.builder,
  bool opaque = false,
  bool maintainState = false,
}) : assert(builder != null),
      assert(opaque != null),
      assert(maintainState != null),
      _opaque = opaque,
      _maintainState = maintainState;
Run Code Online (Sandbox Code Playgroud)