Flutter Web项目API请求遇FormatException问题求助
问题分析与解决方案
核心原因
报错FormatException: //localhost:3030是因为**Uri.http()的第一个参数传入了带http://前缀的地址**(比如http://localhost:3030)。Uri.http()会自动为拼接http://前缀,导致最终生成的URI格式错误(变成http://http://localhost:3030/registration),触发格式异常。
修复步骤
- 确保
registrationUrl的值是不带http:///https://前缀的主机地址,比如直接写localhost:3030。 - 修正请求代码中的URI构建逻辑:
// 正确写法:authority参数仅传主机+端口,不带协议 final response = await http.post( Uri.http('localhost:3030', '/registration'), headers: {"Content-Type": "application/json"}, body: jsonEncode(regBody) ); - 或者改用
Uri.parse()直接传入完整URL,避免手动拼接出错:final fullUrl = 'http://localhost:3030/registration'; final response = await http.post( Uri.parse(fullUrl), headers: {"Content-Type": "application/json"}, body: jsonEncode(regBody) );
额外检查项
- 确认
regBody能被jsonEncode正常序列化,避免因JSON格式错误间接引发异常。 - 验证后端服务在
localhost:3030正常运行,且/registration接口路由配置正确。
内容的提问来源于stack exchange,提问作者Norhassan M. Sarip
相关产品推荐
相关产品推荐

