mvasco
mvasco

Reputation: 5101

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

Upvotes: 1

Views: 644

Answers (4)

jamesdlin
jamesdlin

Reputation: 89995

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.

Upvotes: 1

Majid
Majid

Reputation: 2900

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.

Upvotes: 2

MendelG
MendelG

Reputation: 20038

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()

Upvotes: 4

winfred adrah
winfred adrah

Reputation: 428

Use

 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": _horas.toString()

    });

_horas.toString()

Upvotes: 1

Related Questions