作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在尝试从 initState 中的 Firestore 调用文档时遇到问题。我可以从 StreamBuilder 中提取数据就好了,但我只想在 initState 上调用一次数据。
这是我在做什么:
class _PainLevelState extends State<PainLevel> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final CollectionReference userCollection =
Firestore.instance.collection('users');
static final now = DateTime.now();
String _uid;
double myPainLevel = 0;
Future<void> getCurrentUser() async {
final FirebaseUser user = await _auth.currentUser();
if (mounted) {
setState(() {
_uid = user.uid;
});
}
}
Future<void> getCurrentPainLevel() async {
await userCollection
.document(_uid)
.collection('pain')
.where('time',
isGreaterThanOrEqualTo: DateTime(now.year, now.month, now.day))
.getDocuments()
.then((QuerySnapshot docs) {
if (docs.documents.isNotEmpty) {
print('yes');
} else {
print('no');
}
});
}
@override
void initState() {
super.initState();
getCurrentUser();
getCurrentPainLevel();
}
...
最佳答案
我在这里猜测您的代码不会总是有效,因为 getCurrentPainLevel
可能会在 getCurrentUser
之前被调用完成,这将导致 _uid
为空,因此无法按预期工作。试着放 then
getCurrentUser
之后的关键字方法,像这样:
@override
void initState() {
super.initState();
getCurrentUser().then((_) {
getCurrentPainLevel();
});
}
WidgetsBinding.instance.addPostFrameCallback(...)
.
关于Flutter Firestore getDocuments() 不适用于 initState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62270233/
我是一名优秀的程序员,十分优秀!