Home > Mobile >  Unhandled Exception: type 'int' is not a subtype of type 'String' in type cast i
Unhandled Exception: type 'int' is not a subtype of type 'String' in type cast i

Time:12-13

I am trying to store the latitude and longitude in the database using API using following function:

      Future update_location(latitude,longitude) async {

    var response = await http.post(Uri.parse(ROOT), body: {
      "id": widget.id,
      "action":'update_location',
      "latitude":latitude,
      "longitude":longitude,
    });
    Navigator.pushReplacementNamed(context, Routes.HOME);

  }

and I am passing the argumnets by:

onTap: () async{
              Position position= await _determinePosition();
              print(position.latitude);
              print(position.longitude);
              await update_location(position.latitude, position.longitude);
            },

when I try to do that there is an exception:

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

_EnableLocationState.update_location (package:my_cab_driver/introduction/LocationScreen.dart:26:26) E/flutter ( 4530): #11 _EnableLocationState.build. (package:my_cab_driver/introduction/LocationScreen.dart:163:23) E/flutter ( 4530):

can anyone help me what is wrong here?

CodePudding user response:

In the http post function, the body parameter can be a String, List<int>, or Map<String, String>, but you are passing a Map<String, Object> since you have mixed value types (String and int). I think you probably don't actually want to pass a Map<String, String> since according to the documentation if you did it will assume you are passing data of content type application/x-www-form-urlencoded. If you want to send json data set the content type to application/json and send the body as a string (using json.encode).

var response = await http.post(
  Uri.parse(ROOT),
  headers: {
    'Content-Type': 'application/json',
  },
  body: json.encode({
    "id": widget.id,
    "action": 'update_location',
    "latitude": latitude,
    "longitude": longitude,
  }),
);

The above code requires the following import:

import 'dart:convert';

CodePudding user response:

Try to Use toString() method here and here

like

print(position.latitude.toString());

position.latitude.toString()

CodePudding user response:

I think server giving response as String and you are trying to parse data as int. or may be reverse server giving you value as int & you trying to parse it as String.

  • Related