Search code examples
dartconstructor

Dart 'const' usage with another 'const' values


I need to create class with time range and i want use Duration for this. There is implementation:

final class Timing {
  final Duration lower;
  final Duration upper;

  const Timing.fromDuration(this.lower, this.upper)
      : assert(lower > Duration.zero),
        assert(upper > Duration.zero),
        assert(lower < upper);
}

In another class i create static const fields of Timing class. It is required, cos value of field will be used as default param of method.

class Communicator {
  static constTiming p1 = Timing.fromDuration(
      Duration(milliseconds: 0), Duration(milliseconds: 20));

  void sendMessage(String message, {Duration timeout = p1.lower});
}

Creation of p1 generates Evaluation of this constant expression throws an exception. dart(const_eval_throws_exception) error.

Is there way to group it ? I want to avoid ugly varaibles as p1MaxValueInMillis etc...


Solution

  • You won't be able to use a const with static for this case as "Timing" can't be evaluated at compile time, but final will do the job. You won't be able to access the property of "Timing" as a const to use in a default parameter but you can do this:

    class Communicator {
      static const Duration lower = Duration(milliseconds: 0);
      static const Duration upper = Duration(milliseconds: 20);
      static final Timing p1 = Timing.fromDuration(lower, upper);
    
      void sendMessage(String message, {Duration timeout = lower}) {}
    }