我试图创建一个Future
方法,返回类型为AddressModel
,从Firestore
获取。但我卡住了。
AddressModel类:
class AddressModel{
int pinCode,contactNum;
String fullName,apartment,city,state;
String? area;
String? landmark;
AddressModel({
required this.pinCode,
required this.contactNum,
required this.fullName,
required this.apartment,
required this.city,
required this.state,
this.area,
this.landmark,
});
Map<String, dynamic> toMap() {
return {
'pinCode': pinCode,
'contactNum': contactNum,
'fullName': fullName,
'apartment': apartment,
'area': area,
'landmark': landmark,
'city': city,
'state': state,
};
}
factory AddressModel.fromMap(Map<String, dynamic> map) {
return AddressModel(
pinCode: map['pinCode'] as int,
contactNum: map['contactNum'] as int,
fullName: map['fullName'] as String,
apartment: map['apartment'] as String,
area: map['area'] as String,
landmark: map['landmark'] as String,
city: map['city'] as String,
state: map['state'] as String,
);
}
}
未来方法:
Future<AddressModel?> getAddress(BuildContext context)async{
try{
DocumentSnapshot snapshot = await _fireStore.collection("users").doc(currentUser!.uid).get();
//---------------Stuck Here----------------//
}on FirebaseException catch(e){
showSnackBar(context, e.code.toString());
return null;
}
}
Firestore文档:
修复:(感谢大家的帮助)
QuerySnapshot snapshot = await _fireStore.collection("users").where("uId",isEqualTo: currentUser!.uid).get();
if(snapshot.docs.isNotEmpty){
return AddressModel.fromMap(snapshot.docs[0]['address']);
}
return null;
1条答案
按热度按时间c6ubokkw1#
DocumentSnapshot有一个名为data的特性,因此使用
然后使用AddressModel.fromMap来解析
会是这样的,如果你想在debug中看到:
你也可以加入所有的元素:
你可以在pub firebase_firestore中看到文档:https://pub.dev/documentation/firebase/latest/firebase_firestore/DocumentSnapshot-class.html