0

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?

iDecode
  • 22,623
  • 19
  • 99
  • 186
  • It's the same as in other programming languages (e.g. [Python](https://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python), [C](https://stackoverflow.com/questions/1571340/what-is-the-assert-function), [Java](https://stackoverflow.com/questions/2758224/what-does-the-java-assert-keyword-do-and-when-should-it-be-used), ...). You aren't seeing any effect because you're probably running a release-build of your code where assertions aren't enabled. Run a debug build instead. – jamesdlin May 09 '20 at 06:27

1 Answers1

1

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
  }
}
iDecode
  • 22,623
  • 19
  • 99
  • 186
  • What If I don't put assert check there? I eventually will get the error for null `age` inside `someMethod` and will find the problem and will handle the null value to not get it in the production mode! (because I'll get null related exception eventually inside the method). So I could handle without assert! What is the usage of assert as a whole I can't figure out!!! The thing is I check the errors in debug mode using assert but the checks are useless in production mode. So instead of writing those assert checks I can check the nulls! Hope you get where I have problem. – Davoud Aug 09 '21 at 15:34
  • 1
    @Patzu `assert` only works in the debug mode and you also use debug mode to test your app. So, while testing you made sure no `null` value was getting passed so that in production mode there will be no `null` value. However, with Dart null safety, `assert` carries zero to no meaning. – iDecode Aug 10 '21 at 09:15