Home > database >  How to assert at build time?
How to assert at build time?

Time:09-30

Use case: in a constants.dart file, define a String constant. Make sure that it is a 16-characters in length.

const String myConstant = 'My_16_characters';

Unfortunately, I cannot do assert(myConstant.length == 16), since it would have to be in main() function, which is never executed if importing the file as a library (flutter project).

Would global_assert be the to-go solution, or is there an alternative not requiring a 3rd-part library ?

I will write a unittest for now, but coming from Typescript, this is the kind of check I'd like to have done at typing assertion level.

CodePudding user response:

There is no platform provided way to just ensure that an assert is run at compile time.

The global_assert approach is ingenious, using annotations to force constant expression evaluation and allowing you to put the test almost anywhere. The platform libraries do not have something like that. If you don't want a package dependency just for that, you can easily write it yourself as:

class Assert {
  const Assert(bool test, [Object? message]) : assert(test, message);
}

Then it's just:

@Assert(myConstant.length == 16)
const String myConstant = "My_16_characters";

There are limits to which expressions can be evaluated at compile-time, but string length and == on integers is allowed.

(Sadly, it does not seem like the analyzer evaluates the @Assert annotation, at least based on trying it on DartPad, so you only get the error when calling a compiler.)

  • Related