How do I compare two app versions in flutter?

Issue

I was trying to compare two different app version in flutter,
But I am not able to assign , App versions in a variable.

var a = 1.0.0;
var b = 1.0.1;

But the values not getting assigned in variables.

I think 1.0.0 is not float value, so how to assign that value and compare them ?

Solution

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

void main() {
  String v1 = '1.2.3', v2 = '1.2.11';
  int v1Number = getExtendedVersionNumber(v1); // return 10020003
  int v2Number = getExtendedVersionNumber(v2); // return 10020011
  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.

Answered By – genericUser

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.