【问题标题】:Flutter Firestore getDocuments() not working on initStateFlutter Firestore getDocuments()不适用于initState
【发布时间】: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


    【解决方案1】:

    我在这里猜测您的代码不会总是有效,因为getCurrentPainLevel 可能会在getCurrentUser 完成之前被调用,这将导致_uid 为空,因此无法按预期工作。尝试将then 关键字放在getCurrentUser 方法之后,如下所示:

    @override
      void initState() {
        super.initState();
        getCurrentUser().then((_) {
          getCurrentPainLevel();
        });
      }
    

    顺便说一句,您不应该在 initState 中调用异步方法。尝试将代码放在其他地方,例如WidgetsBinding.instance.addPostFrameCallback(...)

    【讨论】:

    • 现在说得通了。谢谢!我将 initState 更改为WidgetsBinding.instance.addPostFrameCallback((_) =&gt; getCurrentPainLevel()); 并将final FirebaseUser user = await _auth.currentUser(); 添加到getCurrentPainLevel() 方法中,并将_uid 更改为user.uid。现在可以了。 :)
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 2020-11-22
    • 2018-11-16
    • 2020-10-09
    • 2019-11-22
    • 2019-01-28
    相关资源
    最近更新 更多