assert statement in Dart explanation with example

Assert in Dart :

assert statements are useful for debugging a dart project. It is used mainly in development mode. assert takes one expression and checks if it is true or false. If it is true, the program runs normally and if it is false, it stops the execution and throws one error called AssertionError.

Flutter enables it by default for debug mode. It is ignored on production. For other tools like dart, you need to use one command line flag —enable-asserts to enable it. In this tutorial, I will use dart to execute a program and I will show you how to use —enable-asserts.

Syntax :

The syntax of assert is as below :

assert(condition, message)

condition : It is the condition to check message : This is optional. If the condition is false, AssertionError is thrown with the message

Example 1 : assert example without message :

Consider the below program :

import 'dart:io';

main() {
  print("Enter an even number : ");
  int evenNo = int.parse(stdin.readLineSync());

  assert(evenNo % 2 == 0);

  print("You have entered : $evenNo");
}

In this program, we are getting one integer as user input (evenNo). The assert statement checks if it is divisible by 2 or not. If it is not, it will throw one error.

Create one file example.dart with this program and use the below command to execute it :

dart --enable-asserts example.dart 

Without —enable-asserts, assert statement will not test the condition.

If the user enters one odd number, it will throw one AssertError.

Dart assert example

Example 2 : assert example with message :

As explained before, we can use one message with an assert statement :

import 'dart:io';

main() {
  print("Enter an even number : ");
  int evenNo = int.parse(stdin.readLineSync());

  assert(evenNo % 2 == 0, "$evenNo is not even");

  print("You have entered : $evenNo");
}

For an odd input, say 13, it will throw one error like below :

Enter an even number : 
13
Unhandled exception:
'file:///Users/cvc/Documents/sample-programs/dart/example.dart': Failed assertion: line 7 pos 10: 'evenNo % 2 == 0': 13 is not
 even
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:40:39)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:7:10)
#3      _startIsolate.< anonymous closure=""> (dart:isolate-patch/isolate_patch.dart:305:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

More readable than the previous one.