Skip to content

Proposal: replace _duration in Duration with final inMicroseconds #4325

Closed as not planned
@timcreatedit

Description

@timcreatedit

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 Durations 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 numbers to work with in a const context.

Alternatives I've considered:

  1. Performing my arithmetic in a getter – not desirable in a lot of cases and pointless performance overhead
  2. Waiting for more const language features – unsure when they'd arrive an if they would cover this use-case
  3. Using a double in the constructor – worse API, it would need to be called durationInSeconds or something, which isn't very user-friendly

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions