Search code examples
flutterdartcastingtype-systems

Implications of automatic casting with double on dart/flutter


What are the implications of using an int were a double is required? dart allows you to declare a double without the .0 if it is 0 and handle that as a double without any kind of runtime casting?

Thinks that makes me worry about this:

  • I dont see any linter saying that this will cast the int into a double.
  • It compiles fine.
  • The height field is a double but it accepts an int.

Take a look to the examples:

int version

SizedBox(height: 10)

# Or 
final double a = 2;

double version

SizedBox(height: 10.0)

# Or 
final double a = 2.0;

Solution

  • If you look at the SizedBox implementation you'll see that the field height has the type double. enter image description here

    To understand what happens in your code that you have as example you have to understand how type inference works. In the first code example that you gave (int version), even if you wrote 10 and not 10.0 the Dart compiler infer that value as a double because the filed height is of that type. You do not specify explicitly that the value that you give as parameter is int so it's seen as double. If you give as value an integer (you specify the type int) you'll have the next compile-time error:

    enter image description here

    So, to conclude this, in both of your examples Dart infer the type as double because you don't say explicitly that is an integer.

    You can read more about Dart type inference here: https://dart.dev/guides/language/type-system#type-inference