简体   繁体   中英

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.

So what is the meaning of assert ?

assert is used for debugging and it simply means the condition should be true to proceed. 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:

class MyClass {
  final int age;

  MyClass({this.age}) : assert(age != null, "Make sure age isn't null");

  void someMethod() {
    // using `age` here
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM