In this tutorial you will learn about the Dart Assert Statement and its application with practical example.
Dart Assert Statement
The assert statement is a useful debugging tool, is used for testing boolean conditions. An assert statement disrupt normal execution if a boolean condition is false. If the boolean expression is true, then the code continues to execute normally. If assert statement results in false, then execution ends with an AssertionError.
Syntax:-
1 |
assert(<expression>) |
Example:-
1 2 3 4 5 |
// Make sure the str has a non-null value. assert(str != null); // Make sure the num is less than 50. assert(num < 50); |
Note :- Assert statements have no effect in production mode; it is used in development mode only.
Enable Assert
1 |
dart --enable-asserts <file_name>.dart |
Assert with Message
To attach a message to an assert statement, pass a string as the second argument.
Syntax:-
1 |
assert(<expression>, "<message>") |
The first argument is an expression that evaluates to a boolean value. If the expression’s value is true, the assertion succeeds and execution continues. If it’s false, an exception is thrown with the message provided.