flutterdart

How to compare two app versions in Flutter?


I was trying to compare the two app versions in Flutter:

final v1 = "1.0.0";
final v2 = "1.0.1";

How do I state which version is bigger than the other?


Solution

  • Compare them as integers!

    A cool solution is to convert each version to an exponential integer so that we can compare them simply as integers!

    void main() {
      String v1 = '1.2.3', v2 = '1.2.11';
      int v1Number = getExtendedVersionNumber(v1); // return 102003
      int v2Number = getExtendedVersionNumber(v2); // return 102011
      print(v1Number >= v2Number);
    }
    
    int getExtendedVersionNumber(String version) {
      List versionCells = version.split('.');
      versionCells = versionCells.map((i) => int.parse(i)).toList();
      return versionCells[0] * 100000 + versionCells[1] * 1000 + versionCells[2];
    }
    

    Checkout this running example on Dartpad.