jsonDecodeDurationInSeconds function
Converts a dynamic value to a Duration in seconds.
Handles double values with milliseconds precision. Returns Duration.zero for invalid or null input.
durationInSecondsFromJson('1.5'); // 0:00:01.500000
durationInSecondsFromJson(1.5); // 0:00:01.500000
durationInSecondsFromJson(1); // 0:00:01.000000
durationInSecondsFromJson(null); // 0:00:00.000000
Implementation
Duration jsonDecodeDurationInSeconds(final dynamic value) {
if (value == null) return Duration.zero;
Duration handleDouble(final double value) {
final seconds = value.floorToDouble().toInt();
return Duration(
seconds: seconds,
milliseconds: ((value - seconds) * 1000).toInt(),
);
}
return switch (value) {
final double value => handleDouble(value),
final int value => Duration(seconds: value),
final String value => () {
final doubleSeconds = double.tryParse(value);
if (doubleSeconds != null) return handleDouble(doubleSeconds);
final intSeconds = int.tryParse(value);
if (intSeconds != null) return Duration(seconds: intSeconds);
return Duration.zero;
}(),
_ => Duration.zero,
};
}