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

Flutter解析JSON时循环失效问题求助

问题描述

尝试通过Dart解析API返回的JSON数据,编写了FeatureModel类和apiCall方法,但解析时循环卡在i=0;移除featureModel.add(FeatureModel.fromJson(decode[i]))语句后,循环能正常执行到10。相关代码及API响应如下:

模型类代码

class FeatureModel {
  String? PlanFeatures;
  bool? FeatureStatus;

  FeatureModel({this.PlanFeatures, this.FeatureStatus});


  FeatureModel.fromJson(parsonJson) {
    PlanFeatures = parsonJson['PlanFeatures'];
    FeatureStatus = parsonJson['FeatureStatus'];
  }
}

API调用代码

List<FeatureModel> featureModel = [];

Uri featureAPI = Uri.parse(planFeatureApi);
apiCall() async {
  try {
    http.Response response = await http.get(featureAPI);

    if (response.statusCode == 200) {
      var decode = json.decode(response.body);
      print(decode);
      for (var i = 0; i < decode.length; i++) {
        print(i);
        featureModel.add(
          FeatureModel.fromJson(decode[i]),
        );
      }
    }
  } catch (e) {}
}

API响应示例

[{"PlanFeatures":"Video Link Sharing","FeatureStatus":"true"},{"PlanFeatures":"Email & Telephonic Support","FeatureStatus":"true"},{"PlanFeatures":"Remove Pixeshare Branding","FeatureStatus":"false"},{"PlanFeatures":"Add Custom logo on uploaded photos","FeatureStatus":"false"},{"PlanFeatures":"Get Visitor Info","FeatureStatus":"false"},{"PlanFeatures":"Mobile Apps","FeatureStatus":"false"},{"PlanFeatures":"Send Questionnaries","FeatureStatus":"false"},{"PlanFeatures":"Create & Send Quotation","FeatureStatus":"false"},{"PlanFeatures":"Online Digital Album Sharing","FeatureStatus":"false"},{"PlanFeatures":"Analytics","FeatureStatus":"false"}]

错误原因

  1. 类型不匹配触发异常:API返回的FeatureStatus是字符串类型("true"/"false"),但模型类中FeatureStatus定义为bool?类型,直接赋值会触发类型转换异常。
  2. 空catch块静默吞异常:apiCall中的catch (e) {}未做任何处理,异常被静默捕获,导致循环在第一次执行featureModel.add(...)时直接终止,表现为i始终停在0。

修复方案

1. 修正模型类的JSON解析逻辑

将字符串类型的FeatureStatus转换为bool类型:

class FeatureModel {
  String? planFeatures; // 遵循Dart小驼峰命名规范,提升可读性
  bool? featureStatus;

  FeatureModel({this.planFeatures, this.featureStatus});

  FeatureModel.fromJson(Map<String, dynamic> json) {
    planFeatures = json['PlanFeatures'];
    // 将字符串转为bool类型
    featureStatus = json['FeatureStatus'] == 'true';
  }
}

2. 完善异常处理

在catch块中打印错误信息,方便调试:

apiCall() async {
  try {
    http.Response response = await http.get(featureAPI);

    if (response.statusCode == 200) {
      var decode = json.decode(response.body);
      print(decode);
      featureModel.clear(); // 避免多次调用时数据重复累加
      for (var i = 0; i < decode.length; i++) {
        print(i);
        featureModel.add(FeatureModel.fromJson(decode[i]));
      }
    }
  } catch (e) {
    print('解析错误: $e'); // 打印异常信息,便于定位问题
  }
}

额外建议

  • 遵循Dart命名规范:类成员变量使用小驼峰命名(如planFeatures代替PlanFeatures),统一代码风格。
  • 每次调用apiCall前清空列表,避免多次触发接口导致数据重复累加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:50:13