【问题标题】:Getting data from specific document ID in Firebase Firestore with Flutter使用 Flutter 从 Firebase Firestore 中的特定文档 ID 获取数据
【发布时间】:2022-01-16 06:26:13
【问题描述】:

我对 Firebase 还是很陌生,我一直在试图弄清楚如何在每次点击时在 Firebase 中获取特定文档的特定数据。

我将不胜感激。

这是我的列表视图显示我在数据库中输入的所有数据的地方。

当我点击其中一个字段时,此窗口会显示我需要添加的每个员工的信息。

这是我的数据库类代码:

class DataBaseService {
  final String uid;
  DataBaseService({this.uid});

  //collection reference
  final CollectionReference MyEmployees =
      FirebaseFirestore.instance.collection('employees');
  Future<void> updateEmployeeInfo(
    String firstName,
    String lastName,
    String profession,
    String status,
    String email,
    String phone,
    String birth,
    String address,
    String taxNumber,
    String major,
    double salary,
  ) async {
    return await MyEmployees.doc(uid).set(({
      "firstName": firstName,
      "lastName": lastName,
      "profession": profession,
      "status": status,
      "email": email,
      "phone": phone,
      "birth": birth,
      "address": address,
      "taxNumber": taxNumber,
      "major": major,
      "salary": salary,
    }));
  }

 
  // Get employees
  Future getEmployeesList() async {
    List itemList = [];

    try {
      await MyEmployees.get().then((querySnapshot) {
        querySnapshot.docs.forEach((element) {
          itemList.add(element.data());
        });
      });
      return itemList;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}


数据库:

【问题讨论】:

标签: firebase flutter google-cloud-firestore


【解决方案1】:

如果您想查询特定用户,您必须将uid 添加到您的用户模型中。

Future<void> updateEmployeeInfo(
    String firstName,
    String lastName,
    String profession,
    String status,
    String email,
    String phone,
    String birth,
    String address,
    String taxNumber,
    String major,
    double salary,
  ) async {
    return await MyEmployees.doc(uid).set(({
      "uid": uid, //Add this line
      "firstName": firstName,
      "lastName": lastName,
      "profession": profession,
      "status": status,
      "email": email,
      "phone": phone,
      "birth": birth,
      "address": address,
      "taxNumber": taxNumber,
      "major": major,
      "salary": salary,
    }));
  }

当您想获取该特定用户时,您可以像这样查询它:

await MyEmployees.doc(Employee.uid).get();

假设您创建了与您的 Firestore 集合匹配的 Employee

【讨论】:

  • 我听从了您的指示,我还创建了一个 Employee 类,因为我没有,但是当我尝试获取数据时,我只得到一个“未来的实例
  • 而我在数据库中添加的uid由于某种原因得到了一个空值
  • 您必须确保在写入 Firestore 时传递的 uid 不为空。当您获取数据时,您必须将其存储在某个地方。例如:final jsonData = await MyEmployees.doc(Employee.uid).get();
  • 非常感谢您的帮助,但我需要更多说明,我应该如何传递 uid 使其不为空?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2020-11-05
  • 1970-01-01
  • 2021-07-20
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多