Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart const class argument checking

How does one perform argument checking on const class?

For example:

class Data {
    String value;
    const Data(this.value);
}

How can I check that for example value.contains("banana") == true?

If I try to check it in assert like below, linter reports error Invalid constant value. dart(invalid_constant)

class Data {
    String value;
    const Data(this.value)
        : assert(value.contains("banana");
}
like image 251
Peter Avatar asked Aug 09 '26 17:08

Peter


1 Answers

class Data {
    String value;
    const Data(this.value)
        : assert(value.contains("banana");
}

Well for one, you are missing a parenthesis after your assertion. For another, in a constant class, all the fields must be marked as final.

But the last thing (which is what is actually relevant to your question) is that if your constructor is marked as const, then all values and operations in your assertions have to be constants. This is because constant instances are initialized at compile-time and the compiler can't perform assertions where it has to run code in order to validate the constructor data.

This means you can perform things like equality or other boolean operator checks against other constant values:

  : assert(value == 'banana');

But you can't compare against non-constant values or do things like call methods (note: the shown errors are not the errors that the compiler will actually report):

  : assert(value == Foo());           // Error: Foo is not a constant
  : assert(value.contains('banana')); // Error: method calls are not a constant operation
  : assert(value == const Bar());     // Error: Bar is not a compiler-known constant

That last error may be a little obtuse seeing as Bar is a constant class object. The reason it doesn't work, though, is because in order to implement == (the boolean equals operator), Bar has to define code for that operator, and the compiler can't run code in constant assertions. The end result is that, even if an object is marked as a constant, it still can't be used in an assertion. You can only use primitive constants, i.e. Null, bool, int, double, String.

like image 173
Abion47 Avatar answered Aug 11 '26 11:08

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!