man*_*nta 5 dart firebase flutter google-cloud-firestore
我有以学生和教师为类型的约会集合以及其他字段。reference
我想使用 获取约会列表CollectionReference.withConverter。但由于引用字段,我无法获取它们。
示例代码:
FirebaseFirestore.instance.collection('appts').withConverter<Appointment>(
fromFirestore: (snapshot, _) {
Map<String, dynamic> appt = snapshot.data()!;
Student student = await appt['student'] // <---- Error as await is NOT allowed here
.get()
.then((studentSnapshot) => Student.fromMap(studentSnapshot.data()!));
return Appointment.fromMap(
snapshot.data()!
..['id'] = snapshot.id
..['student'] = student,
);
},
toFirestore: (appointment, _) => ...,
);
Run Code Online (Sandbox Code Playgroud)
await不允许,因为withConverter<Appointment>期望fromFirestore返回Appointment对象而不是Future<Appointment>
如果没有await,我会得到Future<Student>,并且不确定如何将完整文档映射到学生类型。
Flutter 的 Firestore 是否会自动获取参考文档,而不是我手动获取它们?
以下是一些可以帮助您处理文档的示例。
在 flutter 中使用 withCoverter withConverter 现在,您可以在不同的地方使用 withConverter 来更改此类型:
DocumentReference.withConverter:
final modelRef = FirebaseFirestore
.instance
.collection('models')
.doc('123')
.withConverter<Model>(
fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);
Run Code Online (Sandbox Code Playgroud)
DocumentReference.withConverter(公共文档)
CollectionReference.withConverter:
final modelsRef = FirebaseFirestore
.instance
.collection('models')
.withConverter<Model>( fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);
Run Code Online (Sandbox Code Playgroud)
CollectionRefence.withConverter(公共文档)
查询.withConverter:
final personsRef = FirebaseFirestore
.instance
.collection('persons')
.where('age', isGreaterThan: 0)
.withConverter<Person>( fromFirestore: (snapshot, _) => Person.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);
Run Code Online (Sandbox Code Playgroud)
Query.withCoverter(公共文档)
这里还有一些 firebase、flutter 的文档:
https://firebase.flutter.dev/docs/firestore/usage/ https://firebase.google.com/docs/reference/js/v8/firebase.firestore.CollectionReference
| 归档时间: |
|
| 查看次数: |
1533 次 |
| 最近记录: |