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

Flutter调用API解析数据时String不是Description类型子类型报错

问题解决方法

报错原因

你的Branchlist数据模型结构与API实际返回的JSON结构不匹配:模型中description字段的类型被声明为自定义的Description类,但API返回的对应字段实际为纯字符串,类型校验不通过就抛出了type 'String' is not a subtype of type 'Description'错误。

修复步骤

  • 第一步:修改branch_list.dart模型文件中description字段的类型定义,将Description类改为String类型:
// 错误写法示例
class BranchListElement {
  Description description;
  // 其余字段
}

// 修正后写法
class BranchListElement {
  String description;
  // 其余字段
}
  • 第二步:补充状态变量存储解析后的数据,修正接口请求逻辑,解析成功后刷新UI:
// 在_restaurantPageState类中新增状态变量,存储解析后的门店列表
List<BranchListElement> branchList = [];

Future getapidata() async {
  String url =
      "https://www.mobilonsoft.com/fpsapi/default.aspx?op=branch_list&firmuid=feedmekktc&device_id=web_20210813180900001&device_platform=4&lang=en";
  try {
    Response responsee = await get(Uri.parse(url));
    if (responsee.statusCode == 200) {
      Map sonuc = jsonDecode(responsee.body);
      Branchlist liste = Branchlist.fromJson(sonuc);
      // 赋值给状态变量,触发UI刷新
      setState(() {
        branchList = liste.result.branchList;
        counter = branchList.length;
      });
      print(branchList);
    }
  } catch (e) {
    print(e.toString());
    print("verileri çekerken hata oluştu");
  }
}
  • 第三步:修正ListView渲染逻辑,使用解析后的门店列表数据渲染:
itemBuilder: (context, index) {
  final currentBranch = branchList[index];
  return ListTile(
    title: Text(currentBranch.branchName),
    subtitle: Text(currentBranch.description),
    leading: CircleAvatar(
      backgroundImage: NetworkImage(currentBranch.branchImg ?? ""),
    ),
  );
}

额外注意

你当前代码中使用的personalResult变量是之前测试其他接口遗留的变量,和当前接口返回结构不匹配,渲染时记得替换为本次解析得到的branchList变量。

内容的提问来源于stack exchange,提问作者Arda Özdiker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:21:02