【问题标题】:The method 'data' was called on null在 null 上调用了方法“数据”
【发布时间】:2021-07-24 21:53:06
【问题描述】:

我创建了这个函数来获取文档(帖子)的用户 ID,但文档总是为空。 有什么想法可以解决这个问题吗? (我使用 Flutter 和 Cloud Firestore)

Future<String> getUserId(String text) async{
var docu;
await FirebaseFirestore.instance
    .collection('post')
    .where('content', isEqualTo: '$text')
    .snapshots()
    .listen((snapshot){
   snapshot.docs.forEach((document) {
    docu = document;
    print('docUserId : ${document.data()['userId']}'); // this works well
  });
});
return docu.data()['userId']; } 

我也试过只返回带有这样字符串的文档 userId

Future<String> getUserId(String text) async{
String docUserId;
await FirebaseFirestore.instance
    .collection('post')
    .where('content', isEqualTo: '$text')
    .snapshots()
    .listen((snapshot){
   snapshot.docs.forEach((document) {
    docUserId = document.data()['userId'];
    print('docUserId : ${docUserId}'); // this works well
  });
});
return docUserId; } 

虽然 print('docUserId : ${docUserId}');该命令运行良好,最终返回值始终为空。 我找不到原因。

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    这里需要注意三个重点:

    1. 如果您只想获取一次数据,则不需要实时监听器
    2. 您不能等待听众。您的函数将始终在您获取数据之前结束。
    3. 使用前检查文档是否存在

    你能用这段代码试试吗:

    import 'package:cloud_firestore/cloud_firestore.dart';
    
    Future<String> getUserId(String text) async {
      String userUid = '';
      QuerySnapshot docSnap = await FirebaseFirestore.instance
          .collection('post')
          .where('content', isEqualTo: '$text')
          .get();
    
      docSnap.docs.forEach((DocumentSnapshot document) {
        if (document.exists) {
          userUid = document.data()['userId'];
          print('docUserId : ${document.data()['userId']}');
        }
      });
    
      return userUid;
    }
    
    

    【讨论】:

      【解决方案2】:

      document.data()

      改成

      docu = 文档;

      print('docUserId : ${docu['userId']}');

      【讨论】:

      • 然后检查firebase数据。快照是否存在
      猜你喜欢
      • 2021-12-18
      • 2021-08-01
      • 2020-01-17
      • 2020-02-21
      • 2020-08-31
      • 2020-08-29
      • 2021-02-11
      • 2021-01-19
      相关资源
      最近更新 更多