firebase - 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 我该怎么做?
解决方案
在等待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');
}
推荐阅读
- elasticsearch - 无法启动 Kibana 7.5.0 致命错误 has not done any changes in configuration file
- java - Spring boot 2.2.1-无法启动嵌入tomcat(日志中没有错误)
- c++ - 如何从文件中对数组中的单个列进行冒泡排序?C++
- laravel - 对于 Laravel 中的每个循环
- r - 使用 glmnet 缩放时预测分数分布的显着变化
- wpf - WPF在可视化树中查找文本块的列索引
- node.js - 如何使用basic-ftp模块连接到节点中的FTPS服务器
- telegram - 使用电报中的内联按钮转移控制(机器人)
- ios - Xcode 错误:无法解析 IPHONEOS_DEPLOYMENT_TARGET:无法解析版本组件来自:'0
- python - 模块“张量流”没有属性“日志”