In Dart, the implements clause in an extension type ensures that the extension type has the same instance members as the implemented type, but it does not inherit static members (like zero, min, hoursPerDay, etc.). This is a deliberate design choice:
Why Static Members Aren't Inherited:
-
Static Members Are Not Part of the Interface:
implements guarantees that your type satisfies the interface of the implemented type (instance methods/getters/setters).
- Static members (including constants like
zero) are class-level members, not instance members, so they're excluded.
-
Extension Types Are Wrappers, Not Subtypes:
- Extension types provide a zero-cost abstraction over an existing type.
- They don't establish a subtype relationship (unlike
extends), so static members aren't propagated.
Solution: Explicitly Redeclare Static Members
To expose Duration's static members (like zero), redeclare them in UnsignedDuration:
extension type UnsignedDuration._(Duration _d) implements Duration {
// Expose Duration's static constants
static const zero = UnsignedDuration._(Duration.zero);
// Redeclare other needed static members
static const int hoursPerDay = Duration.hoursPerDay;
static const int minutesPerHour = Duration.minutesPerHour;
static const int minutesPerDay = Duration.minutesPerDay;
// ... add others as needed
// Factory constructors (with validation)
factory UnsignedDuration({
int days = 0,
int hours = 0,
int minutes = 0,
int seconds = 0,
int milliseconds = 0,
int microseconds = 0,
}) {
final duration = Duration(
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds,
microseconds: microseconds,
);
if (duration.isNegative) throw ArgumentError('Duration must be non-negative');
return UnsignedDuration._(duration);
}
factory UnsignedDuration.fromDuration(Duration duration) {
if (duration.isNegative) throw ArgumentError('Duration must be non-negative');
return UnsignedDuration._(duration);
}
}
Key Notes:
-
Instance Members Work Automatically:
final d = UnsignedDuration(hours: 2);
print(d.inMinutes); // 120 (works because it's an instance member)