首页 > 解决方案 > Flutter 和 Firebase 管理员和普通用户登录

问题描述

你好,我是flutter和firebase的新手,我在用户文档中有一个名为admin的字段,它是一个布尔值,我想在登录功能中检查这个布尔值。到目前为止我想出的是:

onPressed: () async {
  if (_formKey.currentState.validate()) {
    if (!await user.signIn(_email.text, _password.text)) {
      toast("Signin Faild");
    } else {
      if(await _firestore.collection('users').doc(_auth.currentUser.uid).get().)
        changeScreenReplacement(context, HomePage());
      toast("Signedin successfully");
    }
  }
},

我不知道这部分该怎么做: if(await _firestore.collection('users').doc(_auth.currentUser.uid).get().)

我想在这里检查该字段是否等于 true 或 false 我该怎么做?

标签: firebaseflutter

解决方案


在等待get()调用后,您将拥有一个DocumentSnapshot实例,您可以从中读取数据。

DocumentReference上调用get()总是返回DocumentSnapshot实例,即使数据库中不存在文档。所以你可能还需要检查它。

如果数据库中不存在此类文档,则在DocumentSnapshot上调用 data()也将返回 null。

所以这至少可以用两种方式来写。

明确检查数据库中是否存在文档。

final userSnapshot = await _firestore.collection('users').doc(_auth.currentUser.uid).get();

if(userSnapshot.exists) {
  if(userSnapshot.data()['admin'] == true) {
    toast('User is admin');
  } else {
    toast('User not admin');
  }
} else {
  toast('User document not exist in database');
}

或者简而言之,只是忽略用户文档可能不存在的事实。

final userSnapshot = await _firestore.collection('users').doc(_auth.currentUser.uid).get();
if(((await _firestore.collection('users').doc(_auth.currentUser.uid).get()).data() ?? const {})['admin'] == true) {
  toast('User is admin');
} else {
  toast('User not admin or user document not exist');
}

推荐阅读