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

Flutter中Supabase嵌套响应转自定义模型类型不匹配报错求助

解决方法

1. 修复模型中的类型不匹配问题

你的fromJson工厂方法存在类型赋值错误(比如把字符串赋值给int类型字段),这会引发隐性运行时问题,先修正:

修正后的ShopModel

class ShopModel {
  final int? id;
  final int? adrnr;
  final int? industry;
  final String shop_name;
  final int? currency;

  const ShopModel({
    this.id,
    this.adrnr,
    required this.industry,
    required this.shop_name,
    required this.currency,
  });

  factory ShopModel.fromJson(Map<String, dynamic> json) {
    return ShopModel(
      id: json['id'] as int?,
      adrnr: json['adrnr'] as int?,
      industry: json['industry'] ?? 1,
      shop_name: json['shop_name'] ?? '',
      currency: json['currency_id'] as int?,
    );
  }
}

修正后的ShopInRelationshipModel

class ShopInRelationshipModel {
  final int? id;
  final int? shop_id;
  final String? uid;
  final int relationship_type;
  final ShopModel? shop;

  const ShopInRelationshipModel({
    this.id,
    required this.shop_id,
    required this.uid,
    required this.relationship_type,
    required this.shop,
  });

  factory ShopInRelationshipModel.fromJson(Map<String, dynamic> json) {
    return ShopInRelationshipModel(
      uid: json['uid'] ?? '',
      shop_id: json['shop_id'] as int?,
      id: json['id'] as int?,
      relationship_type: json['relationship_type'] ?? 1,
      shop: json['shop'] != null ? ShopModel.fromJson(json['shop']) : null,
    );
  }
}

2. 显式转换列表类型

Supabase返回的response是List<dynamic>类型,直接调用map.toList()会返回List<dynamic>,必须显式指定泛型类型解决类型不匹配错误:

List<ShopInRelationshipModel> shopInRelationshipList;

final response = await _supabase.client
    .from('shop_relationship')
    .select('*, shop(*)')
    .eq('uid', userId);

// 方式1:用List.from指定泛型
shopInRelationshipList = List<ShopInRelationshipModel>.from(
  response.map((e) => ShopInRelationshipModel.fromJson(e as Map<String, dynamic>))
);

// 方式2:显式强转
shopInRelationshipList = (response as List<dynamic>)
    .map((e) => ShopInRelationshipModel.fromJson(e))
    .toList() as List<ShopInRelationshipModel>;

核心说明

  • 类型错误的根源是Dart无法自动推断map后的列表类型,必须显式指定泛型或强转。
  • 模型中要保证字段类型和fromJson赋值的类型完全一致,避免隐性崩溃。
  • 嵌套的shop字段需判断是否为null,防止传入空值调用ShopModel.fromJson引发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:55:30