【问题标题】:How to Solve "Expected a value of type 'int', but got one of type 'String'如何解决“期望一个'int'类型的值,但得到一个'String'类型的值
【发布时间】:2022-01-03 08:13:33
【问题描述】:

我的 api 有这个 post 请求,它需要一个 json 对象数组,例如:

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

我的功能:

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");
    }
  }

}

抛出错误:

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

我不知道如何映射那个身体,我尝试了很多东西。哪种方法更好?

编辑:

完整的堆栈跟踪here

【问题讨论】:

  • 错误指的是什么?你能发布堆栈跟踪吗?
  • @ScottHunter 发布了堆栈跟踪。基本上当用户想要从世界中删除一个对象时调用该函数。

标签: flutter


【解决方案1】:

尝试添加这个

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

它告诉 Flutter 你要插入什么类型的数据。对我有用。

【讨论】:

  • 错误:期望一个“int”类型的值,但得到一个“IdentityMap”类型的值是我用这种方式替换正文时的错误
【解决方案2】:

错误到底在哪里?它在正文请求中吗?如果是的话,试试这个身体部位。希望对你有帮助

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

【讨论】:

  • 这也表示预期类型 int 得到类型字符串。我不得不在正文中添加方括号,因为它需要一个 json 对象数组。
猜你喜欢
  • 2020-11-12
  • 2021-11-26
  • 2022-12-05
  • 2021-12-27
  • 2022-01-08
  • 2021-09-13
  • 2021-03-16
  • 2021-09-18
  • 2020-12-03
相关资源
最近更新 更多