You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中_CastError错误修复:TextEditingController无法转为String

修复Flutter中的_CastError异常

问题原因

调用http.post时,你直接将TextEditingController对象作为请求体的值传入,但后端需要的是字符串类型数据,这就引发了类型不匹配的转换错误。

解决方法

通过控制器的text属性获取输入框中的文本内容,而非传入控制器对象本身。修改saveProduct方法的请求体部分即可:

Future saveProduct() async {
  final response =
      await http.post(Uri.parse("http://127.0.0.1:8000/api/products"), body: {
    "name": _nameController.text,
    "description": _descriptionController.text,
    "price": _priceController.text, // 若后端要求数字类型,可转换为对应类型,比如 double.parse(_priceController.text)
    "image_url": _imageUrlController.text
  });
}

额外提示

  • 如果后端接口要求price为数字类型,记得对_priceController.text做类型转换,同时建议用double.tryParse替代double.parse,避免输入非数字内容时崩溃。
  • 提交前可通过_formKey.currentState?.validate()验证表单输入合法性,确保字段符合要求。

内容的提问来源于stack exchange,提问作者Ali Mustadji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:15:52