【问题标题】:Get the id of a firestore document in flutter在flutter中获取firestore文档的id
【发布时间】:2022-07-22 05:12:27
【问题描述】:

按照颤振文档代码到send data to a new screen 后,我想在详细信息屏幕中检索 todo 实例的 firestore id。有没有办法做到这一点? 这是详细信息屏幕:

  const DetailScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final todo = ModalRoute.of(context)!.settings.arguments as Todo;

    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(todo.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(todo.description),
      ),
    );
  }
}

【问题讨论】:

  • 您最近是否将 todo 实例存储在 Firestore 中?如果还没有firestore ID,您可以分配自己的或自动生成一个。如果存储了 todo 实例但您没有 ID,则可能需要对其他一些属性使用查询才能再次找到该实例。
  • @Chris 实例存储在 firestore 中并具有自动生成的 id。我想我可以查询所有属性以找到特定实例。但是,我不知道如果文档有这么多字段是否是一个好习惯。

标签: flutter firebase dart google-cloud-firestore


【解决方案1】:

当从数据库存储或读取项目时,您应该保留文档 ID 的句柄。然后,当您移动到详细信息页面时,您可以对 todo 实例的文档 ID 进行 firebase 查找,如下所示:

final docRef = db.collection("myCollection").doc(todoId);
docRef.get().then(
  (DocumentSnapshot doc) {
    final data = doc.data() as Map<String, dynamic>;
    // ...
  },
  onError: (e) => print("Error getting document: $e"),
);

This answer 涵盖在颤动屏幕之间发送数据。请参阅Firebase docs here

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 2019-05-05
    • 2020-12-05
    • 2021-12-16
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多