Flutter中如何读取Firestore用户的isadmin字段判断是否为管理员
问题原因分析
你遇到的报错是因为cloud_firestore包中DocumentSnapshot对象的data()方法不接受任何位置参数,该方法会返回当前文档完整的Map<String, dynamic>?类型数据,你不能直接把要读取的字段名作为参数传入这个方法。同时你原有代码还存在混用await和.then、无明确返回值、未兼容空安全的问题。
正确实现方案
这里给出两种常用的稳定实现方式:
方式1:先取全量文档数据再读取字段
Future<bool> checkIsAdmin(String userId) async { try { final docSnapshot = await FirebaseFirestore.instance .collection('users') .doc(userId) .get(); // 先判断对应uid的用户文档是否存在 if (!docSnapshot.exists) return false; final docData = docSnapshot.data(); return docData?['isadmin'] == true; } catch (e) { // 网络请求/权限异常场景默认返回非管理员身份 return false; } }
方式2:直接读取单个字段
如果仅需要校验isadmin状态,不需要获取其他用户字段,可以直接调用get()方法读取单个字段,减少性能损耗:
Future<bool> checkIsAdmin(String userId) async { try { final docSnapshot = await FirebaseFirestore.instance .collection('users') .doc(userId) .get(); if (!docSnapshot.exists) return false; return docSnapshot.get('isadmin') == true; } catch (e) { return false; } }
调用示例
因为方法是异步的,调用时需要用await接收返回结果:
bool isAdmin = await checkIsAdmin(当前登录用户uid); if (isAdmin) { // 执行管理员专属逻辑 }
内容的提问来源于stack exchange,提问作者Black Eyed Beans
相关产品推荐
相关产品推荐

