【问题标题】:adding authenticated user to firestore 'users' collection flutter将经过身份验证的用户添加到 firestore 'users' 集合颤动
【发布时间】:2021-11-02 13:05:26
【问题描述】:

我被困在将经过身份验证的用户添加到 firestore 'users' 集合中。

Unhandled Exception: [cloud_firestore/not-found] Some requested document 
was not found.

用户通过 Google 登录:

class GoogleSignInProvider extends ChangeNotifier {
final GoogleSignIn _googleSignIn = GoogleSignIn();

GoogleSignInAccount _user;

GoogleSignInAccount get user => _user;

AuthService auth = AuthService();

Future googleSignIn(BuildContext context) async {
try {
  final googleUser = await _googleSignIn.signIn();
  if (googleUser == null) return;

  _user = googleUser;

  final googleAuth = await googleUser.authentication;

  final AuthCredential credential = GoogleAuthProvider.credential(
      idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);

  await FirebaseAuth.instance.signInWithCredential(credential);
  } catch (e) {
  print(e.toString());
}

final User currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null)
usersRef.add(currentUser.uid);

Navigator.of(context).pushReplacement(
    CupertinoPageRoute(builder: (_) => TabScreen()));
notifyListeners();
}

但是,无论我如何以及如何尝试身份验证,firebase id 都不会添加到 usersRef(firestore 集合)中。我该如何解决?

我的 Firestore 规则是:

match /users/{userId}/{documents=**} {
  allow read: if request.auth.uid != null;
  allow write, update, create, delete: if isOwner(userId);
}
 function isOwner(userId) {
return request.auth.uid == userId;
}

帮助非常感谢!

【问题讨论】:

  • 你能展示你从firestore和dart firestore代码的实际响应吗?
  • 嗨,@Mariano,应用程序登录,但是当我需要编辑配置文件时,firestore 给出了上述错误:没有要更新的文档。这是 bcoz 身份验证的用户不在 firestore 集合中。
  • 那么,你的问题是什么?您是否正在尝试创建一个 Firebase 集合?您无法修改尚未创建的内容。 Firebase auth 只能修改 Firebase auth 记录,仅此而已。如果你不显示 usersRef 有什么,我们就无法知道发生了什么。
  • aan,我明白了。我确实有 Firestore 收藏。我需要将经过身份验证的用户添加到它。

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


【解决方案1】:

这样做。

Map data = {};
FirebaseFirestore.instance
    .collection('usersCollection')
    .doc(currentUser.uid)
    .set(data);

代替 usersRef.add(currentUser.uid);

当你有 doc id 时使用 set,当你想要一个自动生成的 id 时使用 add

【讨论】:

  • 出现类型错误。未处理的异常:InternalLinkedHashMap' 不是“String”类型的子类型...我的 google 登录未设置 uid,未获取 google 用户的电子邮件和用户名。不明白为什么?它可能是缓存数据吗?但我确实清理了 Firestore 用户数据...多次卸载应用
  • 用您想要添加为数据的内容替换数据。例如。 {name:'客户名称',地址:'xxx'}
  • @HaKim 我认为这应该可以解决您的问题。试试看有没有运气?
【解决方案2】:

所以这解决了我的问题:

final User currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser != null)
    await usersRef.doc(currentUser.uid).set({'email': 
user.email, 'username': user.displayName, 'photoUrl': 
user.photoURL});

我想,我想多了..

谢谢大家的指导和帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-18
    • 2017-12-27
    • 2013-08-20
    • 1970-01-01
    • 2019-09-27
    • 2020-11-26
    • 2020-01-27
    • 2019-06-26
    相关资源
    最近更新 更多