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

Flutter中如何处理Supabase RPC返回的动态类型数据?

处理Supabase RPC返回的dynamic数据并转换为Product对象列表

步骤1:调用RPC并安全转换类型

调用Supabase RPC函数后,返回的dynamic本质是SQL函数输出的产品列表结构,只需将其显式转换为List<Map<String, dynamic>>即可。为避免类型转换错误导致崩溃,建议用安全转换逻辑:

final supabase = Supabase.instance.client;

// 调用RPC函数,传入目标餐厅ID参数
final response = await supabase.rpc(
  'get_non_restaurant_products',
  params: {'restaurant_id': targetRestaurantId}, // 替换为你的实际参数
);

// 安全转换为List<Map<String, dynamic>>,转换失败返回空列表
final List<Map<String, dynamic>> productMaps = 
    response is List ? (response as List).cast<Map<String, dynamic>>() : [];

步骤2:转换为Product对象列表

这一步和你之前处理from('product').select()返回数据的逻辑完全一致,借助map方法结合Product类的转换方法(比如fromMap工厂构造函数)完成转换:

假设你的Product类实现如下:

class Product {
  final int id;
  final String name;
  final double price;
  // 其他产品字段...

  Product({required this.id, required this.name, required this.price});

  // 从Map转换为Product对象的工厂方法
  factory Product.fromMap(Map<String, dynamic> map) {
    return Product(
      id: map['id'] as int,
      name: map['name'] as String,
      price: (map['price'] as num).toDouble(),
      // 其他字段对应赋值...
    );
  }
}

执行转换:

final List<Product> products = productMaps.map(Product.fromMap).toList();

注意事项

  • 确保SQL函数get_non_restaurant_products返回的列名和Product类的字段完全匹配(Supabase默认返回蛇形命名列,比如product_name,如果你的类用小驼峰productName,需要在SQL里用AS重命名列,或者在fromMap里做字段映射)。
  • 如果RPC返回单个对象而非列表(你的场景是产品列表,大概率不会),则转换为Map<String, dynamic>后直接生成单个Product对象即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:56:07