我需要从新创建的文档中获取并保存文档ID.如何从Future返回此id,或者如何将docRef.id添加到客户端提供程序?

  Future<void> saveNewClient(client) async {
    try {
      DocumentReference docRef = await _db.collection('client').add(client);
      client.updateClientId(docRef.id);  <<<< CLIENT PROVIDER
    } catch (e) {
      print(e);
    }
    return;
  }

这段代码不会抛出错误,但它永远不会到达client.updateClientId(docRef.id)行.保存工作,所以我应该能够得到docRef. id.

为什么要跳过这一行?

UPDATE:个 既然我已经从saveNewClient函数获得了文档id,我该如何使用该变量将id添加到客户端提供程序中呢?以下是代码:

Future<String?> clientId =
          firestoreService.saveNewClient(toMap(newClient));
      ref.read(clientNotifierProvider.notifier).updateClientId(clientId);

因为客户ID是future 的,所以我需要等待它被填充.我该怎么做呢? 谢谢

推荐答案

根据您的偏好或使用情况,有几种方法可以实现这一点

 Future<String?> saveNewClient(client) async {
    FirebaseFirestore _db = FirebaseFirestore.instance;
    try {

      /// You can generate a document id before the create operate
      String id = _db.collection("client").doc().id;

      /// pass the generated id to the doc reference and set it
      /// .toMap() -> Assuming your client isn't of type map
      await _db.collection('client').doc(id).set(client.toMap());
      /// upon success return the id
      return id;
    } catch (e) {
      print(e);
      /// or return null if the operation failed
      return null;
    }
  }

Flutter相关问答推荐

如何从模型列表中生成DropdownButtonFormField?

Flutter版本3.19.2需要更新版本的Kotlin Gradle插件./android/build.gradle:ext.kotlin_version = latest-version>'

想更新ListView上的索引点击块Flutter

Riverpod状态管理-在调用请求时更新用户界面

Flutter /dart 列表.第一个子类列表中的Where()错误

将列表<;Events>;从Flutter 应用程序中的函数传回EventLoader属性时出错

如何将带有参数的函数传递给FIFTH中的自定义小部件

如何在巡逻测试期间重新启动dart 侧应用程序状态?

找不到任何与 com.google.firebase:firebase-sessions:[15.0.0, 16.0.0) 匹配的版本

为什么我们需要使用ChangeNotifierProvider而不是仅仅使用ChangeNotifier?

在 Flutter 中显示有关提供者通知的对话框

如何正确地将 PageView 设置为 AppBar 的标题?

如何设置行中项目之间的空格相等?

Flutter blue plus 库,当try 从 esp32 驱动程序获取 PlatformException 时读取特性

如何在 Flutter 中的 BackdropFilter.blur 中制作一个 100x100 的清晰孔

在不丢失游戏状态的情况下从 Flame 游戏导航到 Flutter 小部件

单元测试中如何比较NaN和NaN是否相等

CircleAvatar 在 ListTile 中领先

在自动完成中 Select 值后保持键盘焦点

Flutter:如何将 AssetImage 转换为 Unit8List?