Flutter使用Model向Firebase Firestore添加数据报错求解决方案
问题分析与解决步骤
你的代码报错核心原因有两个:
- Firestore的
add()方法需要接收**Map<String, dynamic>类型**的数据,而你直接传入了Product对象,Firestore无法识别该类型。 - 你定义的
Product构造函数是命名参数构造函数(用{}包裹参数),但创建对象时用了位置参数的写法,这本身就会导致编译错误。
步骤1:修改Product类,添加转Map方法
在Model/Product.dart中,给Product类增加一个toMap()方法,用于将对象转换为Firestore可接受的Map结构,同时可以调整构造函数以适配创建方式:
class Product { String? name; int? stock; String? price; String? getirPrice; String? trendyolPrice; // 改成位置参数构造函数,方便快速创建对象 Product( this.name, this.stock, this.price, this.getirPrice, this.trendyolPrice, ); // 新增:将Product对象转为Firestore可识别的Map Map<String, dynamic> toMap() { return { 'name': name, 'stock': stock, 'price': price, 'getirPrice': getirPrice, 'trendyolPrice': trendyolPrice, }; } }
步骤2:修正HomePage中的数据添加逻辑
在Screens/HomePage.dart的按钮点击事件里,调用Product的toMap()方法,将对象转为Map后传入add(),同时加上异常捕获方便排查问题:
FirebaseFirestore db = FirebaseFirestore.instance; // ... Scaffold( body: Column( children: [ ElevatedButton( child: Text("Ekle"), onPressed: () async { try { // 创建Product对象 Product newProduct = Product("Test", 1, "Test", "Test", "Test"); // 转成Map后添加到Firestore await db.collection("Products").add(newProduct.toMap()); print("数据添加成功"); } catch (e) { print("添加失败:$e"); } }, ), ], ), );
额外提示
如果后续需要从Firestore读取数据并转为Product对象,可以在Product类中补充工厂构造函数:
factory Product.fromMap(Map<String, dynamic> map) { return Product( map['name'], map['stock'], map['price'], map['getirPrice'], map['trendyolPrice'], ); }
内容的提问来源于stack exchange,提问作者Emir Bolat
相关产品推荐
相关产品推荐

