'Parsing double to String is not accepted in function

I need to convert a double variable to string to upload it as part of a http post request to the server:

  final response = await http.post(Uri.parse(url), body: {
      "fecha_inicio": _fechaInicioBBDD,
      "fecha_fin": _fechaFinalBBDD,
      "latitud": _controllerLatitud.text,
      "longitud": _controllerLongitud.text,
      "calle": _controllerDireccion.text,
      "descripcion": _controllerDescripcion.text,
      "tipo_aviso": tipoAviso,
      "activar_x_antes": double.parse(_horas.toString())

    });

The parameter "activar_x_antes": double.parse(_horas.toString()) is throwing an exception when executing the app:

Unhandled Exception: type 'double' is not a subtype of type 'String' in type cast

The value for _horas = 4.0



Solution 1:[1]

When you are doing:

double.parse(_horas.toString())

this is converting _horas to a String and then again to a double. Instead, only call toString():

"activar_x_antes": _horas.toString()

Solution 2:[2]

Let's take a closer look at why this is happening.

You have value _horas = 4.0; which is a double, you are trying to convert it to String to send it to the server. However, you are using double. parse.

Let's look at the parse doc. it says "Parse source as a double literal and return its value." in fact, you are parsing a number String back to double again!

What you can do is either

"activar_x_antes": _horas.toString()

or

"activar_x_antes": '$_horas'

I hope the explanation helps.

Solution 3:[3]

The documentation for http.post states:

body sets the body of the request. It can be a String, a List<int> or a Map<String, String>.

Since you are passing a Map, all keys and values in your Map are required to be Strings. You should not be converting a String to a double as one of the Map values.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MendelG
Solution 2
Solution 3 jamesdlin