What is "assert" in Dart?

Tue, Dec 6, 2022

Read in 2 minutes

In this post we we learn what "assert" keyword is in Dart programming language.

In Dart, the assert keyword is used for assertions, which are used to check for logical errors in code during development. An assertion is a statement that checks a Boolean condition and throws an exception if the condition is false.

The assert keyword takes a Boolean expression as its argument. If the expression is true, the program continues to run as normal. If the expression is false, an AssertionError is thrown.

Here’s an example of using the assert keyword to check if a value is not null:

void main() {
  String? name = 'Alice';

  assert(name != null, 'Name must not be null');

  print('Name: $name');
}

In this example, we declare a nullable String variable name and assign it a value of 'Alice'. We then use the assert keyword to check if name is not null. If name is null, the program throws an AssertionError with the message 'Name must not be null'.

The assert keyword is typically used during development to catch logical errors early in the development cycle. Assertions can be disabled in production code to improve performance. To disable assertions, use the --enable-asserts=false command line option when running the Dart VM.

Here’s an example of disabling assertions:

dart --enable-asserts=false my_program.dart

In this example, the --enable-asserts=false option disables assertions when running the my_program.dart program.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "as" in Dart language?
What is "abstract" in Dart language?
Everything you need to know about Dart language
What is Dart programming language in a nutshell?
Begginer's guide to using List in Dart/Flutter