Dijon
Dijon

Reputation: 123

The type 'double' is not a subtype of type 'String'

It is giving me an error when I try to parse my double value. Price is a String which I am trying to parse into a double but when I try to do that, it gives me an error. I don't know why I am getting this error since double.parse would turn the price into a double.

      price: double.parse(
        element.get('price'),
      ),

The error is Unhandled Exception: type 'double' is not a subtype of type 'String'

Upvotes: 5

Views: 10357

Answers (1)

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12383

double.parse or int.parse need to parse Strings. Your error is because the value that is being passed is not a String, but infact a double.

Change this in your code:

price: double.parse(element.get('price').toString()),

That should work. You can also enhance it by using tryParse:

price: double.tryParse(element.get('price').toString()) ?? 0,

This is in case double.parse fails, and returns a null, your class\function will throw an exception. But using tryParse will try to parse it, and accepts nulls, but if this does return null, you are handling it by assigning it a value of 0.

Upvotes: 9

Related Questions