Search code examples
dartconstants

Dart: How to require function to pass constant values as arguments


I have a function fun that requires a constant value val of type MyType (that can be constant), something like this:

/// [val] should only accept constant values
void fun(MyType val) {
  ...
}

So, for example, this would work:

fun(const MyType('Hello'));

But not this:

var randomValue = Random().nextDouble().toString();
fun(MyType(randomValue));

Is fun possible in Dart?


Solution

  • According to Christopher Moore in a comment, this is not possible. As a result, an alternative solution is needed and it will vary depending on your particular use case.

    For my specific use case, the alternative that I came up with is to use a class that uses the singleton and builder patterns.