Dart - const constructor: Initializing a class member using a function

Viewed 1401

I want to initialize a couple of final member variables using the same function. Unfortunately dart does not allow function calls within the initializer list of a const constructor:

int fun(int val) => val + 1;

class Foo {
  final int a;
  final int b;
  final int c;
  const Foo(int a, int b, int c)
      : a = fun(a),  <-- this won't compile because 
        b = fun(b),  <-- the constructor
        c = fun(c);  <-- is const
}

I absolutely need the constructor to be a constant expression (in order to maintain compatability with existing third party library code). The only workaround I can think of is to repeatedly copy and paste the entire function body into the initializer list. I have already seen this antipattern used in some flutter libraries. Still I would rather avoid it. Does anybody know of a cleaner solution to the problem?

2 Answers

I don't think it is possible.

create an object resulting of any calculation make the result not const.

The only solution I can think of is to do code generation using tools like source_gen and build_runner, so you can execute your fonction at compile time.

How about defining a factory function with private constructor?

Foo._privateConstructor(int a, int b, int c);

then use

factory Foo(int rawA, int rawB, int rawC) {
int a = func(rawA);
int b = func(rawB);
int c = func(rawC);
return Foo._privateConstructor(a,b,c);
}
Related