Flutter Firebase-如何将用户uid添加到文档

时间:2020-06-20 20:12:17

标签: firebase flutter dart google-cloud-firestore firebase-authentication

我想将用户uid添加到添加的任何文档中。

我设法通过以下代码获取uid:

Future getCurrentUser() async {
  final FirebaseUser user = await _auth.currentUser();
  final uid = user.uid;
  print(uid);
  return uid.toString();
}

,我想在这里添加它:

void addData(){
  databaseReference.collection(("ads"))
    .add({
      'category': '$category',
      'location': '$location',
      'subject': '$adName',
      'userId': '$userid',
  });
}

当我尝试在类中定义变量userid时,出现以下错误:

错误:应该是班级成员。 (位于[hpxksa]的expected_class_member

lib / Screens / add_ad.dart:59) 错误:只能在初始化程序中访问静态成员。

如果我在窗口小部件中声明它,它将记录在数据库中,如下所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

getCurrentUser()是异步的,因此它返回Future的实例,您必须执行以下操作:

void addData()async{
  String userid = await getCurrentUser();
  databaseReference.collection("ads").add({
      'category': '$category',
      'location': '$location',
      'subject': '$adName',
      'userId': '$userid',
  });
}