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

Flutter调用insert函数触发FormatException异常问题求助

Flutter插入数据时FormatException问题排查

问题代码

Future<void> insert()async{
  try{
    if( _formKey.currentState!.validate()){
      String Url="http://10.0.2.2/class/insert.php";
      var res=await http.post(Uri.parse(Url),body: {
        "title":_titlecontroller.text.toString(),
        "desc":_descriptioncontroller.text.toString(),
        "desc1":_description1controller.text.toString(),
        "desc2":_description2controller.text.toString(),
        "desc3":_description3controller.text.toString(),
        "code":_codecontroller.text.toString(),
        "code1":_code1controller.text.toString(),
        "code2":_code2controller.text.toString(),
      });
      var response=jsonDecode(res.body);

      if (response["success"]==true) {
        print("success");
      } else {
        print("some issue");
      }
    }
    else{
      Utils.showErrorMessage("Enter all fields", context);
    }
  }
  catch(e){
    Utils.showErrorMessage("$e", context);
    print(e);
  }
}

错误信息

I/flutter (13861): FormatException: Unexpected character (at character 1)
I/flutter (13861): <br />
I/flutter (13861): ^

问题原因

这个错误的核心是:你用jsonDecode解析的后端返回内容不是合法JSON,而是HTML的<br />换行标签。说明后端的insert.php脚本执行出错,输出了HTML格式的错误提示(PHP默认报错会用HTML标签格式化),而非预期的JSON数据。

排查与解决步骤

  • 先查看后端完整返回内容:在Flutter代码的jsonDecode前添加一行print(res.body);,运行后查看控制台输出,能看到后端返回的全部内容,大概率包含具体的PHP错误信息。
  • 直接调试后端接口:用Postman或浏览器发起POST请求到http://10.0.2.2/class/insert.php,传入对应参数,查看返回结果,定位PHP脚本的问题(比如数据库连接失败、SQL语法错误、变量未定义等)。
  • 修正PHP脚本:
    • 确保脚本仅输出JSON格式内容,删除所有调试用的echo/print语句,避免输出非JSON字符。
    • 用json_encode生成返回结果,且在输出JSON前不要有任何HTML标签、空格或其他无关内容。
    • 开发阶段可以开启PHP错误提示,方便定位问题;上线前关闭或用错误日志记录。

内容的提问来源于stack exchange,提问作者Muhammad Zohaib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:37:24