Description
Problem:
As a package author, I want to create a class that takes a duration as an argument in its constructor, and performs some arithmetic with it to set internal fields.
Example code, (that is obviously completely useless):
// This won't compile
class Example {
const Example({
required Duration duration,
required int times,
}) : totalTimeInSeconds = (duration.inMicroseconds / Duration.microsecondsPerSecond) * times;
final double totalTimeInSeconds;
}
However, if I want to make the constructor const
, my hands are tied, since every way to access Duration
s numbers is a getter function, which is not const
.
I assume, that this is the reason why the new SpringDescription.withDurationAndBounce
constructor in flutter is a non-const factory, even though the regular constructor is const: https://github.com/flutter/flutter/pull/164411/files
Proposal
Instead of having the internal _duration
field representing microseconds, turn the inMicroseconds
getter into a final field and use it directly. This will not change the experience for consumers of this class, but it will allow an escape hatch for turning Duration
objects into number
s to work with in a const
context.
Alternatives I've considered:
- Performing my arithmetic in a getter – not desirable in a lot of cases and pointless performance overhead
- Waiting for more
const
language features – unsure when they'd arrive an if they would cover this use-case - Using a double in the constructor – worse API, it would need to be called
durationInSeconds
or something, which isn't very user-friendly