Unable to pass double value in a const constructor

Viewed 51

Minimal reproducible code:

class Foo {
  const Foo.one(Radius radius);

  // Error: Evaluation of this constant expression throws an exception.
  const Foo.two(double radius) : this.one(const Radius.circular(radius));
}

In the Foo.two constructor, why can't I just pass radius which itself is a constant? What's wrong in it?

PS: I don't want to fix the error by removing const from the constructor.

1 Answers

In the expression const Radius.circular(radius), the value of radius is not guaranteed to be const since initializing Foo as const is optional.

When you call a const constructor all of the arguments are required to be const as well, but it can't be guaranteed in this case.

Some people have requested that dart should support some kind of feature like this (github.com/dart-lang/language/issues/2000, github.com/dart-lang/language/issues/823), but it is not possible in dart currently.

An alternative would be to accept a Radius as an argument insted of double.

Related