Flutter集成Firestore添加含嵌套对象的数据失败求助
解决Flutter中Firestore嵌套对象存储失败的问题
我仔细看了你的代码,发现几个关键问题导致嵌套的Grooming对象无法正常存入Firestore,咱们来逐个解决:
1. Grooming类缺少序列化Mixin
你的Grooming类只添加了@JsonSerializable()注解,但没有混入自动生成的序列化Mixin,这会导致grooming.toJson()方法无法正确生成Firestore能识别的Map结构。修改Grooming类:
@JsonSerializable() class Grooming extends Object with _$GroomingSerializerMixin { // 添加这个Mixin int groomingScore; int hairScore; int uniformScore; int decorationScore; int maskWearScore; int maskCleanScore; Grooming(); factory Grooming.fromJson(Map<String, dynamic> json) => _$GroomingFromJson(json); }
修改完成后,重新运行build_runner生成序列化代码:
flutter packages pub run build_runner build
2. 优化Firestore数据添加逻辑
你当前的代码先获取新document再添加,还额外调用setData更新id,这不仅冗余,还可能引发异步时序问题。直接使用document()生成引用,一次性写入所有数据更可靠:
Future<bool> addInspection(Inspection item) async { try { final docRef = inspectionCollection.document(); item.id = docRef.documentID; item.userid = user.uid; // 直接写入完整的序列化对象,包含嵌套的grooming await docRef.setData(item.toJson()); print('Inspection saved successfully!'); return true; } catch (error) { print('Failed to save inspection: ${error.toString()}'); return false; } }
3. 确保Grooming实例已正确初始化
因为你给grooming字段标记了@JsonKey(nullable: false),所以必须保证在创建Inspection对象时,grooming不是null,且所有字段都已赋值,比如:
// 先初始化Grooming对象 final grooming = Grooming() ..groomingScore = 9 ..hairScore = 10 ..uniformScore = 8 ..decorationScore = 7 ..maskWearScore = 10 ..maskCleanScore = 9; // 再创建Inspection对象 final newInspection = Inspection( inspectionDate: DateTime.now(), arrivedTime: '09:00', leaveTime: '17:00', staffName: 'John Doe', postName: 'Front Desk', foundLocation: 'Lobby', guestsProportion: '60%', situationRemark: 'Everything is normal', grooming: grooming, // 传入已初始化的grooming ); // 调用添加方法 await addInspection(newInspection);
做完这些修改后,嵌套的Grooming对象应该能被正确序列化为Map,顺利存入Firestore了。
内容的提问来源于stack exchange,提问作者Sam Choi
相关产品推荐
相关产品推荐

