[英]how should I use assert in Dart?
I saw exmaple code something like:我看到了类似的示例代码:
class ModelBinding extends StatefulWidget {
ModelBinding({
Key key,
this.initialModel = const GalleryOptions(),
this.child,
}) : assert(initialModel != null),
super(key: key);
...
so I wrote something:所以我写了一些东西:
class Person {
String firstName;
Person({name}){
print(name);
}
}
class Employee extends Person {
Employee(String name) : assert(false), super(name: name);
}
main() {
var emp = new Employee('Jason');
}
No matter if it is assert(false)
or assert(true)
, the result is same.不管是
assert(false)
还是assert(true)
,结果都是一样的。
So what is the meaning of assert
?那么
assert
的含义是什么?
assert
is used for debugging and it simply means the condition should be true
to proceed. assert
用于调试,它只是意味着条件应该为true
才能继续。 Let me explain:让我解释:
class MyClass {
final int age;
MyClass({this.age});
void someMethod() {
// using `age` here
}
}
You might face issues in someMethod
if age
passed is null
, so to make sure it isn't null
, you use assert
like:如果
age
是null
,您可能会在someMethod
中遇到问题,因此要确保它不是null
,您可以使用如下assert
:
class MyClass {
final int age;
MyClass({this.age}) : assert(age != null, "Make sure age isn't null");
void someMethod() {
// using `age` here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.