'What assert do in dart?
I just want to know what's the use of assert in a Dart. I was tried to figure it out by myself but I'm not able to do that. It would be great if someone explains to me the use of assert.
Solution 1:[1]
Main purpose of assert
is testing conditions during debugging/development.
Let's think about a real example:
class Product {
Product({
required this.id,
required this.name,
required this.price,
this.size,
this.image,
this.weight,
}) : assert(id > 0),
assert(name.isNotEmpty),
assert(price > 0.0);
final int id;
final String name;
final double price;
final String? size;
final String? image;
final int? weight;
}
We have a Product
class and fields like id
, name
and price
are mandatory but other fields can be handled by generic values as you guess. By asserting required fields, you'll test this data class during debugging/development. Keep in the mind, all asserts ignored in release/production mode;
From the dart.dev#assert:
In production code, assertions are ignored, and the arguments to assert aren’t evaluated.
Comparing to writing tests, even though they are not the same thing, asserts can be very handy with minimal effort, so be generous for writing asserts especially if you don't write tests, it usually rewards you.
Additionally, since constants like kDebugMode
, kReleaseMode
are part of package:flutter/foundation.dart
, another use case is debugMode
specific codes in Non-Flutter
applications. Let's have a look this code:
bool get isDebugMode {
bool value = false;
assert(() {
value = true;
//you can execute debug-specific codes here
return true;
}());
return value;
}
At first it may look confusing but it's a tricky but simple code. An anonymous closure always returns true, so we don't throw any error in any case. Since compiler eliminates the assert statements in release mode, that closure only run in debug mode and mutate the value
variable.
Similarly, you can throw in only debug, from Flutter
source code:
void addAll(Iterable<E> iterable) {
int i = this.length;
for (E element in iterable) {
assert(this.length == i || (throw ConcurrentModificationError(this)));
add(element);
i++;
}
}
That means, it throws only in debug mode, intended for usage in testing your logic.
Nullable Example
For the versions of Dart before 2.12
, your typical example should be look like this:
import 'package:meta/meta.dart';
class Product {
final int id;
final String name;
final int price;
final String size;
final String image;
final int weight;
const Product({
@required this.id,
@required this.name,
@required this.price,
this.size,
this.image,
this.weight,
}) : assert(id != null && name != null && price != null);
}
Solution 2:[2]
From here:
During development, use an assert statement — assert(condition, optionalMessage); — to disrupt normal execution if a boolean condition is false.
Suppose you want to open a URL that must begin with "https"
. How will you confirm this? Here's an example.
Example:
void openUrl({String url}) {
assert(url.startsWith('https'), 'The url should start with https');
// We can proceed as we 'https' in the url.
}
Solution 3:[3]
An assert is similar to an Error in that it is for reporting bad states that should never happen. The difference is that asserts are only checked in debug mode. They are completely ignored in production mode.
Ex:
OverlayEntry({
@required this.builder,
bool opaque = false,
bool maintainState = false,
}) : assert(builder != null),
assert(opaque != null),
assert(maintainState != null),
_opaque = opaque,
_maintainState = maintainState;
Solution 4:[4]
https://dart.dev/guides/language/language-tour#assert During development, use an assert statement — assert(condition, optionalMessage); — to disrupt normal execution if a boolean condition is false. You can find examples of assert statements throughout this tour. Here are some more:
// Make sure the variable has a non-null value. assert(text != null);
// Make sure the value is less than 100. assert(number < 100);
// Make sure this is an https URL. assert(urlString.startsWith('https')); To attach a message to an assertion, add a string as the second argument to assert (optionally with a trailing comma):
assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".'); The first argument to assert can be any expression that resolves to a boolean value. If the expression’s value is true, the assertion succeeds and execution continues. If it’s false, the assertion fails and an exception (an AssertionError) 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 dartdevc typically enable assertions by default. Some tools, such as dart run and dart2js support assertions through a command-line flag: --enable-asserts. In production code, assertions are ignored, and the arguments to assert aren’t evaluated.
Solution 5:[5]
As a programmer, it is very necessary to make an errorless code, and finding errors is very difficult and time taking. Dart provides a solution in the form of assert
to validate your code and to make sure the code will work fine without any error. The assert
is useful in debugging and it uses a boolean condition in its syntax. If the boolean expression in assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error.
Solution 6:[6]
The assert statement is a useful tool to debug the code and it uses boolean conditions for testing. It is very necessary to make an errorless code is very necessary and finding the error is very difficult in a big program. Dart provides the assert statements to check the error.
Syntax: assert(condition);
Make sure the str has a non-null value.
assert(str != null);
Make sure the num is less than 50.
assert(num < 50);
`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | iDecode |
Solution 3 | |
Solution 4 | Mohammed Salim Al-Othman |
Solution 5 | Muhammad Afzal |
Solution 6 |