【问题标题】:String method returning null返回 null 的字符串方法
【发布时间】:2020-07-16 15:52:24
【问题描述】:

我查询了 firebase 并得到了预期的答案,但是,当我返回 String 时,它是 null ...在方法内部它不是 null!

class Util {
  final Firestore firestore = Firestore.instance;
  String name;
  List<User> users = [];

  String getNomeById(bool retirada, String userId) {
    firestore
        .collection('users')
        .where(FieldPath.documentId, isEqualTo: userId)
        .snapshots()
        .listen((snapshot) {
      users = snapshot.documents.map((d) => User.fromDocument(d)).toList();

      if (retirada) {
        name = users[0].name;
        //  print(name); name is here!
      } else {
        name = 'Other';
      }
    });

    return name; // IS NULL
  }
}

【问题讨论】:

  • 为什么你会从 firestore 获得Stream?是否有任何特殊原因,或者您只是想获取该查询返回的内容?
  • @ChristopherMoore 我只是想得到返回的东西

标签: firebase dart google-cloud-firestore


【解决方案1】:

如果您只想获取返回的查询,请使用getDocuments 方法而不是snapshots()。它返回一个Future&lt;QuerySnapshot&gt;。有了这个,您可以使用现有代码正确返回String。例如:

Future<String> getNomeById(bool retirada, String userId) async {
  QuerySnapshot snapshot = await firestore
    .collection('users')
    .where(FieldPath.documentId, isEqualTo: userId)
    .getDocuments();
  
  users = snapshot.documents.map((d) => User.fromDocument(d)).toList();

  if (retirada) {
    name = users[0].name;
  } else {
    name = 'Other';
  }
  return name;
}

【讨论】:

  • 谢谢,但现在...我正在尝试在小部件中使用 return AlertDialog(title: Text(u.getNomeById(retirada, userId) ?? 'teste'), type 'Future ' 不是“String”类型的子类型
  • @Manzini 这应该作为一个单独的问题来问,或者你可以看看其他问题,但你需要await。您应该阅读Futures。
猜你喜欢
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2012-02-05
  • 2012-10-09
  • 2020-09-24
  • 2020-04-13
相关资源
最近更新 更多