Search code examples
flutterdartmathduration

How to directly divide two Duration objects in Dart?


In Dart, let's say you have:

Duration duration01 = Duration(milliseconds: 10000);
Duration duration02 = Duration(milliseconds: 100);

I know that while add or subtract seems to work, doing:

double result = duration01 / duration02;

does not work.

And I know how to do it using basic math by unwrapping and re-wrapping the duration objects... but is there a way to do it directly like I am attempting?


Solution

  • Dividing one Duration by another is not something that most people need to do, so there's no built-in way to do it.

    You always can convert the Duration objects to microseconds and then perform arithmetic. Since Duration does not already have operator /, you can add one as an extension method to make it more convenient:

    extension DurationDivision on Duration {
      double operator / (Duration other) =>
          inMicroseconds / other.inMicroseconds;
    }
    
    void main() {
      Duration duration01 = Duration(milliseconds: 10000);
      Duration duration02 = Duration(milliseconds: 100);
      print(duration01 / duration02); // Prints: 100
    }