【发布时间】:2021-03-02 21:40:43
【问题描述】:
下图显示了我的数据库的结构。每个模型类都是顶级集合。
在我的 userData 集合中,我在用户首次注册时保存了有关用户的其他信息,例如姓名、地址、电话号码等。我可以成功写入 firebase,但我在从 firebase 读取表单字段时遇到问题。
我在下面粘贴了我的 UserData 类模型和 Notifier 类,这样你就可以看到我做了什么。
请在我的 getUserData() 中遗漏什么?还是我做错了?有人可以告诉我一个更好的方法来实现从 Firebase 读取当前登录的用户数据吗?
class User {
final String uid;
final String email;
final String password;
User({this.uid, this.email, this.password});
}
class UserData {
String id;
String firstName;
String lastName;
String phoneNumber;
String role;
String businessName;
String businessType;
String streetAddress;
String city;
String state;
String postcode;
String country;
Timestamp createdAt;
Timestamp updatedAt;
UserData(
this.id,
this.firstName,
this.businessType,
this.businessName,
this.city,
this.country,
this.createdAt,
this.lastName,
this.phoneNumber,
this.postcode,
this.role,
this.state,
this.streetAddress,
this.updatedAt,
);
UserData.fromMap(Map<String, dynamic> data) {
id = data['id'];
firstName = data['first_name'];
lastName = data['last_name'];
phoneNumber = data['phone_number'];
role = data['role'];
businessName = data['business_name'];
businessType = data['business_type'];
streetAddress = data['street_address'];
city = data['city'];
postcode = data['postcode'];
state = data['state'];
country = data['country'];
createdAt = data['created_at'];
updatedAt = data['updated_at'];
}
Map<String, dynamic> toMap() {
return {
'id': id,
'first_name': firstName,
'last_name': lastName,
'phone_number': phoneNumber,
'role': role,
'business_name': businessName,
'business_type': businessType,
'street_address': streetAddress,
'city': city,
'postcode': postcode,
'state': state,
'country': country,
'created_at': createdAt,
'updated_at': updatedAt,
};
}
}
//UserDataNotifier类
class UserDataNotifier with ChangeNotifier {
UserData _currentLoggedInUserData;
CollectionReference userDataRef = Firestore.instance.collection('userData');
UserData get currentLoggedInUserData => _currentLoggedInUserData;
Future<UserData> getUserData() async {
String userId = (await FirebaseAuth.instance.currentUser()).uid;
DocumentSnapshot variable =
await Firestore.instance.collection('userData').document(userId).get();
_currentLoggedInUserData = variable.data as UserData;
notifyListeners();
}
Future createOrUpdateUserData(UserData userData, bool isUpdating) async {
String userId = (await FirebaseAuth.instance.currentUser()).uid;
if (isUpdating) {
userData.updatedAt = Timestamp.now();
await userDataRef.document(userId).updateData(userData.toMap());
print('updated userdata with id: ${userData.id}');
} else {
userData.createdAt = Timestamp.now();
DocumentReference documentReference = userDataRef.document(userId);
userData.id = documentReference.documentID;
await documentReference.setData(userData.toMap(), merge: true);
print('created userdata successfully with id: ${userData.id}');
}
notifyListeners();
}
}
【问题讨论】:
标签: firebase flutter google-cloud-firestore firebase-authentication