Version.fromString constructor

Version.fromString(
  1. String string
)

Version from string.

e.g.

Version.fromString("1.2.3+4") == Version(major: 1, minor: 2, patch: 3, build: 4)

Implementation

factory Version.fromString(String string) {
  var versionString = string;

  // If the version string does not contain a build number, add a 0.
  if (!string.contains("+")) {
    // e.g. 1.2.3 -> 1.2.3+0
    versionString += "+0";
  }

  final version = versionString.split("+");

  if (version.length < 2) {
    throw FormatException("Invalid version string: $string");
  }

  final versionNumbers = version[0].split(".");

  if (versionNumbers.length != 3) {
    throw FormatException("Invalid version string: $string");
  }

  var major = int.parse(versionNumbers[0]);
  var minor = int.parse(versionNumbers[1]);
  var patch = int.parse(versionNumbers[2]);

  var build = int.parse(version[1]);

  return Version(
    major: major,
    minor: minor,
    patch: patch,
    build: build,
  );
}