我在Firestore中有一个文档,其中引用了Firestore中的另一个文档,我想调用第一个文档的构造函数,并同时构建引用的文档。似乎无法使用Future(在构造函数中)时,我会坚持使用Future。
有什么办法让ClassA的构造函数将ClassB的DocumentReference转换为ClassB(可能通过ClassB.fromSnapshot())?
在ClassA中,我尝试了ClassB.fromRef(DocumentReference),但在ClassB中必须返回Future,据我所知,您不能在构造函数中执行Future。在我看到的解决方案中,它们将Future部分推到UI中,调用ClassA,但是我不确定如何处理这样的Text小部件(Text(await classA.classB.toString())?)
我可以通过.then()获取DocumentReference进行解析,但是我不能从该模型调用setState(这很有意义,它是模型,而不是视图)。我看到它正常工作的唯一方法是,如果在我的视图侧,我保留一个要在ListView中显示的字符串数组,然后执行.then(setState()),但这确实很麻烦...
我想,我想要的是能够用ListView
做Item
(ClassA classA = ClassA.fromSnapshot(shapshot);
)并能够呼叫classA.classB.name
。
这两个类如下:
ClassA.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:msd/models/ClassB.dart';
class ClassA {
/// The firestore ID
String id;
String name;
ClassB classB;
String status;
DocumentReference reference;
ClassA({id, name, classB, status, reference}) {
this.id = id;
this.name = name;
this.classB = classB;
this.status = status;
this.reference = reference;
}
ClassA.fromMap(Map<String, dynamic> map, String id, {this.reference}) {
id = id;
name = map['name'];
status = map['status'];
classB = ClassB.fromRef(map['classB']);
}
ClassA.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, snapshot.documentID, reference: snapshot.reference);
String toString() {
return 'ClassA $name at $ClassB';
}
}
ClassB.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
class ClassB {
/// The firestore ID
String id;
String code;
String email;
String name;
String phone;
DocumentReference reference;
ClassB({id, code, email, name, phone, address, reference}) {
this.id = id;
this.code = code;
this.email = email;
this.name = name;
this.phone = phone;
this.reference = reference;
}
ClassB.fromMap(Map<String, dynamic> map, String id, {this.reference})
: assert(map['code'] != null),
assert(map['email'] != null),
assert(map['name'] != null),
assert(map['phone'] != null),
assert(map['address'] != null),
id = id,
code = map['code'],
email = map['email'],
name = map['name'],
phone = map['phone'];
ClassB.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, snapshot.documentID, reference: snapshot.reference);
static Future<ClassB> fromRef(DocumentReference ref) async {
DocumentSnapshot snapshot = await ref.get();
return ClassB.fromSnapshot(snapshot);
}
String toString() {
return '$name <$code>';
}
}