Assert

During development, use an assert statement— assert(condition, optionalMessage); —to disrupt normal execution if a booleancondition is false. You can find examples of assert statementsthroughout this tour. Here are some more:

  1. // Make sure the variable has a non-null value.
  2. assert(text != null);
  3. // Make sure the value is less than 100.
  4. assert(number < 100);
  5. // Make sure this is an https URL.
  6. assert(urlString.startsWith('https'));

To attach a message to an assertion,add a string as the second argument to assert.

  1. assert(urlString.startsWith('https'),
  2. 'URL ($urlString) should start with "https".');

The first argument to assert can be any expression thatresolves to a boolean value. If the expression’s valueis true, the assertion succeeds and executioncontinues. If it’s false, the assertion fails and an exception (anAssertionError) is thrown.

When exactly do assertions work?That depends on the tools and framework you’re using:

  • Flutter enables assertions in debug mode.
  • Development-only tools such as dartdevctypically enable assertions by default.
  • Some tools, such as dart and dart2js,support assertions through a command-line flag: —enable-asserts.

In production code, assertions are ignored, andthe arguments to assert aren’t evaluated.