fromJson method

  1. @override
Duration fromJson(
  1. String json
)

Implementation

@override
Duration fromJson(String json) {
  final match = _regex.firstMatch(json);
  if (null == match) {
    throw FormatException(
      "The provided json data for a duration must be "
      "in the format HH:MM:SS.mmmuuu (e.g.: 00:00:00.000000, "
      "-04:10:02.000103)",
      json,
    );
  }

  final isNegative = null != match.namedGroup("minus");

  final hours = match.namedGroup("hours")?.toInt();
  if (null == hours) {
    throw FormatException(
      "The provided data for a duration does not "
      "contain any data for the hour",
      json,
    );
  }

  final minutes = match.namedGroup("minutes")?.toInt();
  if (null == minutes) {
    throw FormatException(
      "The provided data for a duration does not "
      "contain any data for the minute",
      json,
    );
  }

  final seconds = match.namedGroup("seconds")?.toInt();
  if (null == seconds) {
    throw FormatException(
      "The provided data for a duration does not "
      "contain any data for the second",
      json,
    );
  }

  final milliseconds = match.namedGroup("milliseconds")?.toInt();
  final microseconds = match.namedGroup("microseconds")?.toInt();

  final duration = Duration(
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    milliseconds: milliseconds ?? 0,
    microseconds: microseconds ?? 0,
  );

  return isNegative ? -duration : duration;
}