compareVersions function

int compareVersions(
  1. String v1,
  2. String v2
)

Compare versions v1 and v2 with 0 if same, 1 if v1>v2 and -1 if v1<v2.

Implementation

int compareVersions(String v1, String v2) {
  // Split the version strings into lists of integers.

  List<int> version1 = v1.split('.').map((e) => int.parse(e)).toList();
  List<int> version2 = v2.split('.').map((e) => int.parse(e)).toList();

  // Determine the maximum length to iterate.

  int maxLength =
      version1.length > version2.length ? version1.length : version2.length;

  for (int i = 0; i < maxLength; i++) {
    // If one version has fewer components, assume 0 for the missing components.

    int part1 = i < version1.length ? version1[i] : 0;
    int part2 = i < version2.length ? version2[i] : 0;

    if (part1 < part2) {
      return -1; // v1 is less than v2.
    } else if (part1 > part2) {
      return 1; // v1 is greater than v2.
    }
  }

  return 0; // v1 is equal to v2.
}