【发布时间】:2020-10-06 04:44:27
【问题描述】:
当使用多个 setData 线程写入 Firebase 数据库时,仅解析最后一个线程。例如:
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
await Firestore.instance.collection('stores').document(user.uid).setData({'String1': 'My First String', 'String2': 'My Second String', 'String3': 'My Third String'});
await Firestore.instance.collection('stores').document(user.uid).setData({'String4': 'My Fourth String', 'String5': 'My Fifth String', 'String6': 'My Sixth String'});
return userFromFirebaseUser(user);
} catch(e) {
print('REGISTER EnP ERROR: ' + e.toString());
return null;
}
}
当我创建新用户时,Firebase 数据库中的结果显示如下:
String4: "My Fourth String"
String5: "My Fifth String"
String6: "My Sixth String"
需要能够像这样写入数据库,每次写入都应该在继续之前“等待”完成,但这似乎不是发生的事情。
(编辑)烧烤:
实际代码不是直接使用 setData 编写,而是通过类传递数据。所以而不是:
await Firestore.instance.collection('stores').document(user.uid).setData({'String1': 'My First String', 'String2': 'My Second String', 'String3': 'My Third String'});
await Firestore.instance.collection('stores').document(user.uid).setData({'String4': 'My Fourth String', 'String5': 'My Fifth String', 'String6': 'My Sixth String'});
其实是这样写的:
await DatabaseService1(uid: user.uid).updateUserData(variable1, variable2, variable3);
await DatabaseService2(uid: user.uid).updateUserData(variable4, variable5, variable6);
所以当涉及到批处理类型的解决方案时,我不太清楚如何编写将这些类调用到批处理中然后运行它的语法。
【问题讨论】:
-
请更新您的问题以显示
updateUserData的作用。 -
嗨弗兰克,我已按要求添加了代码。除非我运行另一个线程,否则在将数据填充到我的数据库时一切都很好。和 OHDatabaseService 完全一样。
-
感谢您的更新。我没有立即看出这里出了什么问题。如果您将代码简化为不再使用
DatabaseService类,而是直接从registerWithEmailAndPassword中调用setData(),您还能重现问题吗? -
非常感谢您跟进,弗兰克。我听从了你的建议,直接使用了 setData 。在添加的两行中,它只再次处理了第二行。完全忽略第一行。我会将测试过的代码添加到问题中。
-
不太确定问题出在哪里,但是为什么不使用批量写入来代替(或者如果您也需要读取数据,也可以使用事务)?这样您就可以自动更新数据并确保两个操作都发生了。
标签: firebase flutter dart google-cloud-firestore firebase-authentication