Search code examples
flutterdartgoogle-cloud-firestoreroles

How to display categories based on user role, Firebase Flutter


I have 2 kinds of users "d" and "p".

For them, there is a special collection - roles, which stores the user's uid and his role.

I'm trying to display a role and, based on the role, display the corresponding categories.

However, I am getting the following error.

The argument type 'Future<QuerySnapshot<Object?>>? Function(QuerySnapshot<Map<String, dynamic>>)' can't be assigned to the parameter type 'FutureOr<QuerySnapshot<Object?>> Function(QuerySnapshot<Map<String, dynamic>>)' because 'Future<QuerySnapshot<Object?>>?' is nullable and 'Future<QuerySnapshot<Object?>>' isn't.

What alternatives do I have to implement the same? The action takes place in a function that is then called and processed in the FutureBuilder.

getCategoryData(String _collection, {bool forMap = false}) {

  FirebaseFirestore.instance.collection('roles').where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid).get().then((value){
      for (var element in value.docs) {
        if(forMap == false && element.data()['role'] == 'd'){
          Future<QuerySnapshot> _snapshot = FirebaseFirestore.instance.collection(_collection).where('for_d', isEqualTo: true).get();

          return _snapshot; 
        }else if((forMap == false && element.data()['role'] == 'p') || (forMap == true)){
          Future<QuerySnapshot> _snapshot = FirebaseFirestore.instance.collection(_collection).get();

          return _snapshot; 
        }
      }
  });
}

Solution

  • The problem here is that, there is a chance your getCategoryData function might return a null object.

    If it goes over all the docs and none of them match the given two if conditions, a null value is returned by default.

    Your database design might be such that this might never occur but the compiler is unaware of that.

    You can fix this by returning an empty future after the for loop. The compiler won’t show this error anymore. Although I hope you’ve designed your database well that this condition will never occur.