【发布时间】:2020-09-27 21:36:36
【问题描述】:
我在尝试在 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();
}
...
每次打印到控制台时,我都会得到一个“否”。当有一个文件时,它不会得到任何文件。如果我在未来使用相同的代码并将其放在其他地方,例如在构建方法中,它可以工作,但它会不断构建,我不希望这样。关于它为什么不起作用的任何建议?提前致谢。
【问题讨论】:
标签: flutter dart google-cloud-firestore async-await