assert is a keyword in dart used to do assertions during development.

It helps debug and test boolean expressions during debugging.

It is also used in unit testing for asserting the expected boolean values.

Asserts are similar to errors. The difference is that asserts works in debug mode and is disabled in production mode. Errors

Dart assert

assert gives an error if the expression is false and stops its execution. Assertions are not enabled by default.

Here is syntax

assert(expression,"messagestring");

expression is a boolean expression that always resulted in true or false. if the true, assertion is successful, execution continues, false, execution stops. messagestring is a displayed to the user if the expression is false

In this program, assert expression is true, compile executes normally. Here is an example program

void main() {
  print("one");
  assert(true);
  print("two");
  print("three");
}

Here is an output

one
two
three

Here is an assert false expression example

void main() {
  print("one");
  assert(false, "error in code");
  print("two");
  print("three");
}

Output:

one
Unhandled exception:
'file:///A:/work/dart/set-get.dart': Failed assertion: line 3 pos 10: 'false': error in code       
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:40:5)
#2      main (file:///A:/work/dart/set-get.dart:3:10)
#3      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

How to enable assert in Dart

By default, assert expressions are not working as expected. You need to enable assert using –the enable-asserts option.

dart --enable-asserts  filename

In Flutter, These are enabled during debug mode. dartdevc tools enable assertions enabled by default.

Difference between assert and error in dart?

assert and error are used to give exceptions or errors to the user, and program execution is stopped.

assert is used for debugging the boolean expressions, This will be enabled during debugging mode, It is disabled during production mode. asserts are only enabled in debug builds, disabled in release builds. Error is used to throw a Compile and runtime exceptions Compile-time errors are caught at compile time. Runtime errors are caught at production.

asserts are used for sanity checks for finding logical errors. errors are used for handling unexpected runtime errors.

Advantages with assert

  • Clean code to avoid writing if-else conditions with println to inspect the values
  • These are only for developers, and not called in release and production builds.
  • Useful for unit testing the code