简体   繁体   English

在 flutter 中从 Firebase Firestore 收集字符串

[英]Collecting string from Firebase Firestore in flutter

I am creating like system and i want to get likeCount from firebase which i created.我正在创建类似系统,我想从我创建的 firebase 中获取 likeCount。

我要收集的数据

It's collecting it but returns null, here is my code:它正在收集它但返回 null,这是我的代码:

  String? getLikecount(tresc) {
String? likeCount;
FirebaseFirestore.instance
    .collection('Posty')
    .where('Tresc', isEqualTo: tresc)
    .get()
    .then((value) => value.docs.forEach((element) async {
          var id = element.id;
         final value = await FirebaseFirestore.instance.collection('Posty').doc(id).get();
          
            likeCount = value.data()!['likeCount'].toString();
            print(likeCount);
        }));
print(likeCount);
return likeCount;
}

and here is console output:这是控制台 output:

控制台输出

Data is loaded from Firestore (and most modern cloud APIs) asynchronously, because it may needs to come from the.network and we can't block your code (and your users) while waiting for it.数据从 Firestore(和大多数现代云 API)异步加载,因为它可能需要来自 .network 并且我们不能在等待它时阻止您的代码(和您的用户)。

If we change the print statements a bit, and format the code, it'll be much easier to see what's going on:如果我们稍微更改打印语句并格式化代码,就会更容易看到发生了什么:

String? getLikecount(tresc) {
  String? likeCount;
  FirebaseFirestore.instance
      .collection('Posty')
      .where('Tresc', isEqualTo: tresc)
      .get()
      .then((value) => value.docs.forEach((element) async {
            var id = element.id;
            final value = await FirebaseFirestore.instance
                .collection('Posty')
                .doc(id)
                .get();

            likeCount = value.data()!['likeCount'].toString();
            print('In then: $likeCount');
          }));
  print('After then: $likeCount');
  return likeCount;
}

If you run this, you'll see it outputs:如果你运行它,你会看到它的输出:

After then: null之后:null

In then: 0在那时:0

This is probably not what you expected, but it explains perfectly why you don't get a result.这可能不是您所期望的,但它完美地解释了为什么您得不到结果。 By the time your return likeCount runs, the likeCount = value.data().['likeCount'].toString() hasn't executed yet.当您的return likeCount运行时, likeCount = value.data().['likeCount'].toString()尚未执行。

The solution is always the same: any code that needs the data from the database has to be inside the then handler, be called from there, or be otherwise synchronized.解决方案总是相同的:任何需要数据库数据的代码都必须在then处理程序中,从那里调用,或者以其他方式同步。

In Flutter it is most common to use async and await for this.在 Flutter 中,最常见的是为此使用asyncawait The key thing to realize is that you can't return something now that hasn't been loaded yet.要意识到的关键是你现在不能返回还没有加载的东西。 With async / await you function becomes:使用async / await you function 变为:

Future<String?> getLikecount(tresc) {
  String? likeCount;
  var value = await FirebaseFirestore.instance
      .collection('Posty')
      .where('Tresc', isEqualTo: tresc)
      .get();

  for (var doc in value.docs) {
    var id = element.id;
    final value = await FirebaseFirestore.instance
        .collection('Posty')
        .doc(id)
        .get();

    likeCount = value.data()!['likeCount'].toString();
    print('In then: $likeCount');
  }));

  print('After then: $likeCount');
  return likeCount;
}

Now your code returns a Future<String?> so a value that at some point will hold the string.现在您的代码返回一个Future<String?> ,这样一个值在某个时候将保存该字符串。 When calling getLikecount you will now need to use then or await to handle the Future , and if you want to show the count in the UI you will have to store it in the State of a StatefulWidget .调用getLikecount时,您现在需要使用thenawait来处理Future ,如果您想在 UI 中显示计数,则必须将其存储在StatefulWidgetState中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM