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
相关产品推荐
相关产品推荐

