Firebase中基于角色的身份验证

时间:2020-06-24 07:43:12

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

我尝试通过使用以下代码bu将管理员用户导航到特殊页面,它给出了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")

2 个答案:

答案 0 :(得分:0)

更改此:

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

对此:

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

答案 1 :(得分:0)

您的snapshot.data对象在此处null

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

那是因为如果对象不存在,快照数据将为null。 Google建议先exists检查一下:

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

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