Home > Software design >  Parsing double to String is not accepted in function
Parsing double to String is not accepted in function

Time:03-09

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

If you want to send your body without converting the double value to string. Add an header and Wrap your body with jsonEncode(). Like here;

   final response = await http.post(Uri.parse(url),
    headers: {
              "content-type": "application/json",
            },
    body: jsonEncode({
          "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())
    
        }));
  • Related