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

Flutter中Firebase性能监控未捕获http网络请求,求排查错误

问题排查与修复方案

你的代码存在几个关键问题,导致Firebase性能监控无法捕获网络请求:

1. 性能收集启用方式错误

FirebasePerformance.instance.isPerformanceCollectionEnabled()仅用于检查当前性能收集是否开启,不是启用收集的方法。你需要在用户登录成功后调用setPerformanceCollectionEnabled(true)来开启数据收集,而非在每次请求时await这个检查方法。

2. 未补充HttpMetric关键响应数据

Firebase需要请求的响应状态码、字节数等信息才能正确上报网络指标。拿到response后,必须手动更新metric的核心属性:

if (metric != null) {
  metric.responseCode = response.statusCode;
  metric.responsePayloadSize = response.contentLength ?? 0;
  // 如有请求体,可添加请求字节数统计
  // metric.requestPayloadSize = ...;
}

3. finally块逻辑错误

你使用||运算符会导致冗余分支判断,应该仅在metric不为null时执行stop操作:

finally {
  if (metric != null) {
    await metric.stop();
  }
}

4. URL一致性问题

newHttpMetric传入的URL需和实际请求的URL完全一致。你当前手动拼接URL的方式,可能和Uri.https生成的URL存在编码差异,建议直接复用请求的Uri:

final requestUri = Uri.https(url, query, queryParams);
// 初始化metric时使用该Uri的字符串
metric = FirebasePerformance.instance.newHttpMetric(requestUri.toString(), HttpMethod.Get);
// 请求时直接使用该Uri
var response = await client.get(requestUri, headers: {...});

修复后的完整代码示例

getData(query, [queryParams]) async{
  var token = await GetAndStoreLocalStorageValue().getToken();
  HttpMetric? metric;
  final requestUri = Uri.https(url, query, queryParams);
  
  if(query != '<query for firebase credential>') {
    // 确保登录后已调用FirebasePerformance.instance.setPerformanceCollectionEnabled(true)
    metric = FirebasePerformance.instance
        .newHttpMetric(requestUri.toString(), HttpMethod.Get);

    await metric.start();
  }
  
  try {
    var response = await client.get(
      requestUri,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      }
    );
    
    // 补充响应数据到metric
    if (metric != null) {
      metric.responseCode = response.statusCode;
      metric.responsePayloadSize = response.contentLength ?? 0;
    }
    
    return response;
  } catch(error) {
    // 捕获错误时记录到metric
    if (metric != null) {
      metric.error = error.toString();
    }
    return error;
  } finally {
    if (metric != null) {
      await metric.stop();
    }
  }
}

额外确认事项:

  • Android/iOS项目已正确配置Firebase Performance(包含对应的配置文件、依赖)
  • 用户登录成功后确实调用了FirebasePerformance.instance.setPerformanceCollectionEnabled(true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:27:53