firebaseflutterdartgoogle-cloud-firestorerole-base-authorization

role based authentication in firebase


I tried to navigate admin user to a special page by using following code bu it gives the NoSuchMethodError this is the code

 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();
}
}
}

this is the error I had

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


Solution

  • Your snapshot.data object is null here:

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

    And that's because snapshot data will be null if the object doesn't exist. Google suggests checking that it exists first:

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

    If the DocumentSnapshot points to a non-existing document, getData() and its corresponding methods will return null. You can always explicitly check for a document's existence by calling exists().