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

Flutter调用Laravel新增记录API返回Null问题求助

Flutter调用Laravel新增记录API返回Null问题(Thunder Client测试正常)

开发基于Flutter前端、Laravel后端的移动应用时,新增记录的API通过Thunder Client测试功能正常,但Flutter调用该API却返回Null响应。

错误截图

Flutter相关代码

API调用方法

final _messengerState = scaffoldKey.currentState; // 用于显示snackbar
scanParticipant() async {
    Map data = {
      'event': 1,
      'participant': 11,
      'recorder': 6,
    };
    print(data);

    Response response = await _crud.postRequest(addParticipantRoute, data);
    ...
  }

通用POST请求封装

postRequest(String url, Map data) async {
    try {
      var response = await http.post(Uri.parse(url),
          headers: {"Accept": "application/json"}, body: data);
      return response;
    } catch (e) {
      print('Error catch $e');
    }
  }

Laravel后端代码

public function addRecord(Request $request)
{
    $fields = $request->validate([
        'event' => 'required|integer',
        'participant' => 'required|integer',
        'recorder' => 'required|integer'
    ]);

    $user = Record::where('event',$fields['event'])->where('participant',$fields['participant'])->first();
    
    if($user == null) 
    {
        Record::create([
            'event' => $fields['event'],
            'participant' => $fields['participant'],
            'recorder' => $fields['recorder'],
            'moment' => Carbon::now()->addHour(),
        ]);

        return response([
            'message' => 'success',
        ],201);
    }else {
        return response([
            'message' => 'already scanned'
        ],422);
    }
}

备注

调用该功能前已完成登录操作。

排查方向与解决方案

  • CSRF令牌缺失:Laravel默认对web路由开启CSRF保护,Thunder Client可能自动携带会话令牌,但Flutter请求未携带。解决:将API路由移至routes/api.php(API路由默认关闭CSRF验证);若必须用web路由,需在Flutter请求头中添加X-CSRF-TOKEN,值从登录响应中获取并存储。
  • 请求格式不匹配:Thunder Client默认发送JSON格式,但Flutter的http.post用body: data时默认是application/x-www-form-urlencoded,可能导致Laravel无法解析参数。修改请求:
    // 需导入dart:convert包
    postRequest(String url, Map data) async {
        try {
          var response = await http.post(Uri.parse(url),
              headers: {
                "Accept": "application/json",
                "Content-Type": "application/json"
              }, 
              body: jsonEncode(data));
          return response;
        } catch (e) {
          print('Error catch $e');
          throw Exception('请求失败: $e');
        }
      }
    
  • 异常捕获导致返回Null:当前postRequest捕获异常后仅打印日志,无返回值,会默认返回null。可在catch块抛出异常或返回自定义错误响应,避免调用方拿到null。
  • 路由地址错误:检查Flutter中addParticipantRoute的地址是否与Thunder Client一致,模拟器需用本地IP而非localhost,端口也要匹配。

内容的提问来源于stack exchange,提问作者mouad kaaib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 01:17:21