gpt4 book ai didi

flutter - 断言在 Dart 中做什么?

转载 作者:IT王子 更新时间:2023-10-29 07:18:35 25 4
gpt4 key购买 nike

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

最佳答案

assert 的主要目的是在调试/开发期间测试条件。

让我们考虑一个真实的例子:

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

final int id;
final String name;
final double price;
final String? size;
final String? image;
final int? weight;
}

我们有一个 Product 类,idnameprice 等字段是强制性的,但其他字段可以如您所料,由通用值处理。通过断言必填字段,您将在调试/开发期间测试此数据类。请记住,所有断言在发布/生产模式下都会被忽略;

来自dart.dev#assert :

In production code, assertions are ignored, and the arguments to assert aren’t evaluated.

与编写测试相比,即使它们不是一回事,assert 也可以非常方便,只需很少的努力,因此在编写 assert 时要大方一些,尤其是如果您不编写测试,它通常会给您带来返回。

此外,由于 kDebugModekReleaseMode 等常量是 package:flutter/foundation.dart 的一部分,因此另一个用例是 debugMode Non-Flutter 应用程序中的特定代码。让我们看看这段代码:

bool get isDebugMode {
bool value = false;
assert(() {
value = true;
//you can execute debug-specific codes here
return true;
}());
return value;
}

起初它可能看起来令人困惑,但它是一个棘手但简单的代码。匿名闭包总是返回 true,所以我们在任何情况下都不会抛出任何错误。由于编译器在 Release模式下消除了 assert 语句,因此该闭包仅在 Debug模式下运行并改变 value 变量。

同样,你也可以只调试,来自Flutter源代码:

void addAll(Iterable<E> iterable) {
int i = this.length;
for (E element in iterable) {
assert(this.length == i || (throw ConcurrentModificationError(this)));
add(element);
i++;
}
}

这意味着,它仅在 Debug模式下抛出,用于测试您的逻辑。

可空示例

对于 2.12 之前的 Dart 版本,您的典型示例应如下所示:

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);
}

关于flutter - 断言在 Dart 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56537718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com