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

使用Flutter Parse SDK添加对象失败,但curl请求正常

Flutter Parse SDK 提交对象报错 FormatException: Unexpected end of input

环境与代码

  • 系统:Windows
  • 依赖:最新版Flutter、Parse Server,使用Flutter Parse SDK 4.0.2

Parse初始化代码

await Parse().initialize(
      "myAppId", 
      "http://192.168.1.55:4040/parse/",
      debug: true
    );

添加对象代码

var obj = ParseObject("GameScore");
obj.set<int>("score", 123);
obj.set<String>("playerName", "Ahmed Hammad");
obj.set<bool>("cheatMode", false);
await obj.save();

报错信息

执行上述代码后出现以下错误:

I/flutter (31178): ╭-- Parse Request
I/flutter (31178): curl -X POST -H 'content-type: text/plain; charset=utf-8' -H 'user-agent: Flutter Parse SDK 4.0.2' -H 'X-Parse-Application-Id: myAppId' -d '{"score":123,"playerName":"Ahmed Hammad","cheatMode":false}' http://192.168.1.55:4040/parse/classes/GameScore
I/flutter (31178): 
I/flutter (31178):  http://192.168.1.55:4040/parse/classes/GameScore
I/flutter (31178): ╰--
I/flutter (31178): ╭-- Parse Response
I/flutter (31178): Class: GameScore
I/flutter (31178): Function: ParseApiRQ.create
I/flutter (31178): Status Code: -1
I/flutter (31178): Type: OtherCause
I/flutter (31178): Exception: FormatException: Unexpected end of input (at character 1)
I/flutter (31178): 
I/flutter (31178): ^
I/flutter (31178): 
I/flutter (31178): ╰-- 

关键现象:将日志中的curl命令复制到命令行执行,能够成功添加数据。


排查与解决方案

1. 修正请求Content-Type

日志显示SDK使用的content-type为text/plain; charset=utf-8,但Parse Server预期接收application/json类型。curl可兼容该差异,但Flutter的HTTP解析器对响应格式更敏感,会因此解析失败。修改初始化代码,显式指定Content-Type:

await Parse().initialize(
      "myAppId", 
      "http://192.168.1.55:4040/parse/",
      debug: true,
      contentType: "application/json",
    );

2. 确认移动平台网络权限

如果在Android/iOS设备上运行,检查是否添加了必要的网络权限:

  • Android:在android/app/src/main/AndroidManifest.xml中添加
    <uses-permission android:name="android.permission.INTERNET" />
    
  • iOS:在ios/Runner/Info.plist中添加ATS配置(允许HTTP请求)
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    

3. 配置Parse Server的CORS规则

确保Parse Server允许Flutter应用所在的来源发起请求,修改Parse Server配置:

// Parse Server 配置示例
const api = new ParseServer({
  // 其他配置项...
  cors: {
    origin: "*", // 开发环境可临时使用,生产环境需限制为具体域名/IP
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true
  }
});

4. 捕获详细异常信息

在save()方法外层添加try-catch,获取更完整的错误堆栈,辅助定位问题:

try {
  await obj.save();
} catch (e, stackTrace) {
  print("保存失败:$e");
  print("堆栈信息:$stackTrace");
}

内容的提问来源于stack exchange,提问作者Ahmed Hammad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:52:31