A dart code behaves differently in dartpad and local because of double type

//Works on Dartpad

main() {
  var pi = 3.14; //3.14159265359
  var numbers = 0;
  dynamic result = 1.2;

  while (result.runtimeType == double) {
    numbers++;
    result = numbers * pi;
  }
  print('$result / $numbers = $pi');
}

//Works on local

main() {
  var pi = 3.14; //3.14159265359
  var numbers = 0;
  dynamic result = 1.2;
  while ((result - result.truncate()) != 0) {
    numbers++;
    result = numbers * pi;
  }
  print('${result.truncate()} / $numbers = $pi');
}

The problem is whenever you initialize a double variable, the dartpad can convert it to an integer when it becomes an integer but the local compiler doesn't do that. Could this be caused by js? Because as far as I know dartpad compiles with js.


Solution 1:

What you are observing is Dart trying to hide the limitation of JavaScript where numbers is always represented as double objects (so no int). Since DartPad is compiling your code to JavaScript and then executes it in your browser, you will get this behavior.

For more details I recommend looking at this StackOverflow question where I have made a detailed example that shows how numbers in Dart behave when running your program natively and as JavaScript: Why dart infers the variable type as a int when I explicitly say the type is double?