Home > Software engineering >  How to Solve "Expected a value of type 'int', but got one of type 'String'
How to Solve "Expected a value of type 'int', but got one of type 'String'

Time:11-25

I have this post request to my api that needs an array of json objects like :

[{ 
   "x": 1,
   "y": 1
}]

My function:

Future<String> deleteObstacle(String server, int x, int y) async {
    final response =
        await http.delete(Uri.parse('$server/admin/obstacles/'), headers: {
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*"
    }, body: [
      jsonEncode(<String, int>{"x": x, "y": y})
    ]);
    if (response.statusCode == 200) {
      Map<String, dynamic> launchResponse = jsonDecode(response.body);
      return launchResponse['response'];
    } else {
      throw Exception("ERROR Attempting to Delete obstacle");
    }
  }

}

Throws error:

"Expected a value of type 'int', but got one of type 'String'

Im not sure how to map that body and ive tried an array of things. What approach is better?

Edit:

Full stack trace here

CodePudding user response:

Try to add this

    [{ 
   "x": 1 **as** *int*,
   "y": 1 **as** *int*
}]

It tells Flutter what type of data you're inserting. Works for me.

CodePudding user response:

Where exactly is the error? Is it in the body request? If its, try this for the body part. Hope its help you

 Map<String, int> body = <String, int>{
      'x'      : x,
      'y'      : y,
 };
  final response =
        await http.delete(Uri.parse('$server/admin/obstacles/'), headers: {
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*"
    }, body: jsonEncode(body)
 
  );
  • Related