Search code examples
flutterdartgoogle-cloud-firestorecasting

Dart - int.toDouble() still makes the runTimeType as int if the value is not a fraction


Dart Version 2.10.0

I am using flutter Dart with firestore as backend and have encountered a problem where a value of 1 for a field when stored (after json_seralizer) into a variable of type double, although succeeds, its runtime is still int.

This manifests into a runtime error when assigning the double variable value to another double variable with the error type 'int' is not a subtype of type 'double?' in type cast.

For example:- In Firestore -> rValue: 1

In Dart class -> double rateValue

Serialized through

rateValue = (rValue as num)?.toDouble()

Then later,

double currencyExchangeRate;
currencyExchangeRate = rateValue //throws error at runtime type 'int' is not a subtype of type 'double?' in type cast

Dartpad sample code to see the problem,

import 'dart:math' as math;
void main() {
 
  math.Random rand = math.Random();
  
  int x = rand.nextInt(10);
  
  double a = x.toDouble();
  double b = (x as num).toDouble();
  
  print ('a is $a and ${a.runtimeType} and b is $b and ${b.runtimeType}');
  
}

//Above code prints "a is 7 and int and b is 7 and int"

I have searched a lot of stackoverflow posts for same issue but none has helped so far.

Even with the explicit casting and no dynamic variables the double variables (a and b) still show a runtime type of int.

How can I successfully assign currencyExchangeRate = rateValue and prevent this runtime error?

Thanks.


Solution

  • I have found the cause of the problem I particularly faced in my own flutter dart code.

    Prior to json_serializer being available in dart I had my own manual casting from firestore data into the class and that code was not converting using the .toDouble() method. Hence, the value 1 was being treated as integer still and not as double.

    The partial class that json_seralizer creates with fromJson and toJson methods correctly converts the figure 1 to double in the target class.

    I have removed my own serializer code to now relying on json_serializer generated code in this instance (as I always do otherwise anyway).

    So, no real issue was there with dart conversion, just my oversight in the investigation and I did't spot the fact that my own long-time-ago serializer code was the culprit.

    Json_seralizer does the (e as num)?.toDouble() which correctly converts 1 to 1.0 in the target class.