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)
我们有产品,他们必须有price,id和name。但是我们可以处理其他字段,例如通用图像或空白图像图标等。此外,尺寸和重量也不是必须的。
因此,最后我们必须确保必填字段不能为空,因为它们是强制性的。如果您这样做,您将在开发期间处理空值,而不是在已发布的应用程序上出错。
不要忘记这个(来自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.
从这里:
在开发过程中,使用断言语句—— 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)
断言类似于错误,因为它用于报告不应该发生的不良状态。不同之处在于断言仅在调试模式下检查。它们在生产模式中被完全忽略。
前任:
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)