gpt4 book ai didi

firebase - 在 flutter 中使用 withConverter 获取 Firestore 文档引用字段的数据

转载 作者:行者123 更新时间:2023-12-05 05:56:07 28 4
gpt4 key购买 nike

我有约会学生老师的集合为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, _) => ...,
);

await不允许作为 withConverter<Appointment>期待 fromFirestore返回 Appointment对象而不是 Future<Appointment>

没有await , 我会得到 Future<Student> ,并且不确定如何将完整文档映射到Student 类型。

有没有 Flutter 的 Firestore 自动获取引用文档而不是我手动获取它们?

最佳答案

这里有一些示例可以帮助您处理他们的文档。

在 flutter 中使用 withCoverter带转换器现在,您可以在各个地方使用 withConverter 来更改此类型:

DocumentReference.withConverter:
final modelRef = FirebaseFirestore
.instance
.collection('models')
.doc('123')
.withConverter<Model>(
fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);

DocumentReference.withConverter (公共(public)文档)

CollectionReference.withConverter:

final modelsRef = FirebaseFirestore
.instance
.collection('models')
.withConverter<Model>( fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);

CollectionRefence.withConverter (公共(public)文档)

查询.withConverter:

final personsRef = FirebaseFirestore
.instance
.collection('persons')
.where('age', isGreaterThan: 0)
.withConverter<Person>( fromFirestore: (snapshot, _) => Person.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);

Query.withCoverter (公共(public)文档)

这里还有firebase、flutter的一些文档:

https://firebase.flutter.dev/docs/firestore/usage/ https://firebase.google.com/docs/reference/js/v8/firebase.firestore.CollectionReference

关于firebase - 在 flutter 中使用 withConverter 获取 Firestore 文档引用字段的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69289903/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com