[英]What assert do in dart?
我只想知道 Dart 中的断言有什么用。我试图自己弄清楚,但我做不到。 如果有人向我解释assert的用法,那就太好了。
更新:在下面查看有关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);
}
我们有产品,它们必须有price
, id
和name
。 但是我们可以处理其他字段,例如通用图像或空白图像图标等。此外,尺寸和重量也不是必须的。
因此,最后我们必须确保必填字段不能为空,因为它们是强制性的。 如果您这样做,您将在开发期间处理空值,而不是在已发布的应用程序上出错。
不要忘记这个(来自docs
):
在生产代码中,断言被忽略,断言的参数不被评估。
Null-safety update:
由于这是关于assert
主题,Dart 是否null-able
为null-able
的事实根本不会改变任何东西。 因为assert
就是做出断言。
一个简单的例子是:
final text = Text('foo');
assert(text.data == 'foo', 'The text must be foo!');
但是在我们的具体示例中,我们需要进行一些更改。 因为id
、 name
或price
不能为 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);
}
因为它们是空安全的,我们需要处理zero-values
。
从这里:
在开发过程中,使用断言语句—— assert(condition, optionalMessage); — 如果布尔条件为假,则中断正常执行。
假设您要打开一个必须以"https"
开头的 URL。 你将如何确认这一点? 这是一个例子。
例子:
void openUrl({String url}) {
assert(url.startsWith('https'), 'The url should start with https');
// We can proceed as we 'https' in the url.
}
断言类似于错误,因为它用于报告不应该发生的坏状态。 不同之处在于断言仅在调试模式下检查。 它们在生产模式下完全被忽略。
前任:
OverlayEntry({
@required this.builder,
bool opaque = false,
bool maintainState = false,
}) : assert(builder != null),
assert(opaque != null),
assert(maintainState != null),
_opaque = opaque,
_maintainState = maintainState;
https://dart.dev/guides/language/language-tour#assert在开发过程中,使用断言语句—— assert(condition, optionalMessage); — 如果布尔条件为假,则中断正常执行。 您可以在本教程中找到断言语句的示例。 这里还有一些:
// 确保变量具有非空值。 断言(文本!= null);
// 确保值小于 100。 assert(number < 100);
// 确保这是一个 https URL。 断言(urlString.startsWith('https')); 要将消息附加到断言,请添加一个字符串作为断言的第二个参数(可选地使用尾随逗号):
assert(urlString.startsWith('https'), 'URL ($urlString) 应该以 "https" 开头。'); assert 的第一个参数可以是解析为布尔值的任何表达式。 如果表达式的值为真,则断言成功并继续执行。 如果为 false,则断言失败并抛出异常(AssertionError)。
断言究竟何时起作用? 这取决于您使用的工具和框架:
Flutter 在调试模式下启用断言。 dartdevc 等开发专用工具通常默认启用断言。 一些工具,例如 dart run 和 dart2js,通过命令行标志支持断言:--enable-asserts。 在生产代码中,断言被忽略,断言的参数不被评估。
作为一名程序员,编写无错误的代码是非常必要的,而查找错误是非常困难和耗时的。 Dart 以assert
的形式提供了一种解决方案来验证您的代码并确保代码可以正常工作而不会出现任何错误。 assert
在调试中很有用,它在语法中使用 boolean 条件。 如果 assert 语句中的 boolean 表达式为真,则代码继续执行,但如果它返回假,则代码以断言错误结束。
assert 语句是调试代码的有用工具,它使用 boolean 条件进行测试。 编写无错误的代码是非常必要的,而在大型程序中发现错误是非常困难的。 Dart 提供断言语句来检查错误。
Syntax: assert(condition);
确保 str 具有非空值。
assert(str;= null);
确保 num 小于 50。
assert(num < 50);
`
断言类似于错误,因为它用于报告不应该发生的坏状态。 不同之处在于断言仅在调试模式下检查。 它们在生产模式下完全被忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.