【问题标题】:In Flutter, using await stores data correctly, but not collection name and not using await does not store data correctly, but correct collection name在 Flutter 中,使用 await 正确存储数据,但不是集合名称,不使用 await 并不能正确存储数据,而是正确的集合名称
【发布时间】:2022-02-18 18:36:41
【问题描述】:

我当前的代码使用:

var currentUID = await database.getCurrentUserID();

在这行代码上使用 await 运行此函数会将数据以正确的用户 ID 存储在 Firestore 中,但时间始终设置为 0:

Future<void> addUserTime() async {
  var currentUID = await database.getCurrentUserID();

  return await database.workoutCollection
      .doc(currentUID.toString())
      .set({
        'Workout Time': format(duration),
      })
      .then((value) => print('Time added'))
      .catchError((error) => print('Failed to add time to database'));
}

不使用 await 像上一行这样的代码:

var currentUID = database.getCurrentUserID();

Firestore 显示:这是 firebase 输出。 Firebase 身份验证的用户 ID 错误,但时间始终设置为用户记录的内容:

Future<void> addUserTime() async {
  var currentUID = database.getCurrentUserID();

  return await database.workoutCollection
      .doc(currentUID.toString())
      .set({
        'Workout Time': format(duration),
      })
      .then((value) => print('Time added'))
      .catchError((error) => print('Failed to add time to database'));
}

这是我调用getCurrentUserID() 函数的数据库类:

如何获得正确的 UID 和用户登录的正确时间?

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore async-await


    【解决方案1】:

    FirebaseAuth 存储当前用户一旦在FirebaseAuth.instance.currentUser 中被认证,如果我们查看这个属性我们会发现类型是User?,而不是Future&lt;User?&gt;,因此你不需要await要获取当前用户,只需:

    return FirebaseAuth.instance.currentUser?.uid;
    

    另外,currentUser?.uid 返回一个字符串,所以不需要调用.toString()

    假设持续时间不为 0,通过这些修改,代码应该可以工作,以供进一步参考 here's a DartPad example,它根据 currentUser.uid 更新用户记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多