【问题标题】:role based authentication in firebasefirebase 中基于角色的身份验证
【发布时间】:2020-06-24 07:43:12
【问题描述】:

我尝试使用以下代码将管理员用户导航到一个特殊页面,但它给出了NoSuchMethodError 这是代码

 class Home extends StatelessWidget {

  @override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<DocumentSnapshot>(
  stream: Firestore.instance.collection('users').document(user.uid).snapshots(),
  builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot){
    if(snapshot.hasError){
      return Text('Error: ${snapshot.error}');
    }
    switch(snapshot.connectionState){
      case ConnectionState.waiting: return Loading();
      default:
        return checkRole(snapshot.data);
    }
  
  },
);
 }
Widget checkRole(DocumentSnapshot snapshot){
if(snapshot.data['category']=='admin'){
  return AproveNotice();
}else{
  return HomePage();
}
}
}

这是我遇到的错误

The method '[]' was called on null. Receiver: null Tried calling: []("category")

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore role-base-authorization


    【解决方案1】:

    您的snapshot.data 对象在此处为null

    if(snapshot.data['category']=='admin'){

    这是因为如果对象不存在,快照数据将为空。谷歌建议先检查exists

    https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot

    如果 DocumentSnapshot 指向一个不存在的文档,getData() 及其对应的方法将返回 null。您始终可以通过调用 exists() 显式检查文档是否存在。

    【讨论】:

      【解决方案2】:

      改变这个:

      case ConnectionState.waiting: return Loading();
            default:
              return checkRole(snapshot.data);
          }
      

      到这里:

      case ConnectionState.waiting: return Loading();
      case ConnectionState.done: return checkRole(snapshot.data);
          }
      

      【讨论】:

        猜你喜欢
        • 2020-07-14
        • 2018-07-12
        • 2016-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 2015-05-17
        • 2023-01-24
        相关资源
        最近更新 更多