Flutter对接Firebase时如何将String转换为List<dynamic>
这个报错的核心原因是你存储到Firebase中的products字段不是JSON数组类型,是Dart List对象默认toString后的字符串格式,所以拉取解码后得到的是String类型,无法直接强转为ListorderData['products'].runtimeType的结果也会验证这一点,输出为String而非List。
方案1:临时兼容现有数据(无需修改上传逻辑)
你现在拿到的products字符串格式为({id: xxx, title: xxx, ...}, {id: xxx, ...}),只需要把它转换成标准JSON数组格式再解码即可,替换原来强转List的代码:
// 替换掉你原来products字段的赋值代码 products: (){ String productStr = orderData['products'] as String; // 去掉首尾的括号 productStr = productStr.substring(1, productStr.length - 1); // 用[]包裹内容,形成标准数组格式 productStr = "[$productStr]"; // 给所有键名补双引号,符合JSON格式要求 productStr = productStr.replaceAllMapped(RegExp(r'(\w+):'), (match) => '"${match.group(1)}":'); // 给字符串类型的字段值补双引号 productStr = productStr.replaceAllMapped(RegExp(r':\s*([a-zA-Z\s]+)([,}])'), (match) => ': "${match.group(1)}"${match.group(2)}'); // 解码为List<dynamic> List<dynamic> productList = json.decode(productStr); return productList.map((item) => CartItem( id: item['id'], price: item['price'], quantity: item['quantity'], title: item['title'], )).toList(); }()
方案2:根治问题(推荐,修改上传逻辑)
最好的方式是在上传订单数据到Firebase时,就把products字段序列化为标准的JSON数组,避免后续拉取时的格式处理:
- 先给CartItem类添加toJson方法:
class CartItem { final String id; final double price; final int quantity; final String title; CartItem({required this.id, required this.price, required this.quantity, required this.title}); // 新增toJson序列化方法 Map<String, dynamic> toJson() { return { 'id': id, 'price': price, 'quantity': quantity, 'title': title, }; } }
- 上传订单时,把products列表转换成JSON可识别的List
// 示例上传代码修改 await http.post(Uri.parse(uploadUrl), body: json.encode({ 'amount': order.amount, 'dateTime': order.dateTime.toIso8601String(), // 替换掉原来直接传products.toString()的错误写法 'products': order.products.map((item) => item.toJson()).toList(), }));
修改上传逻辑后,后续新存入的订单拉取时就可以直接用你原来的orderData['products'] as List<dynamic>强转代码,不需要额外处理字符串。
内容的提问来源于stack exchange,提问作者Mohamed Ahmed
相关产品推荐
相关产品推荐

