Home > Net >  Joining a room using invite code in flutter
Joining a room using invite code in flutter

Time:01-13

I'm trying to create a simple game application using flutter. It has a page where users can enter an invite code and press a button to join the room. I have multiple rooms with different names on firebase and each one has a unique inviteCode. How can I write a function to check through all the rooms if the enteredCode matches any of the rooms' invite codes?

This is what I've tried so far:

Future<bool> _checkInviteCode(String enteredCode) async {
    // reference to the Firestore
    final firestore = FirebaseFirestore.instance;
    //get the invite code collection
    final querySnapshot = await firestore.collectionGroup('inviteCode').get();

    // check if the entered code matches any of the invite codes in the Firestore collection
    if (querySnapshot.docs
        .any((doc) => doc.data()['inviteCode'] == enteredCode)) {
      print("Code matched!");
      return true;
    } else {
      print("Invalid code");
    }
    return false;
  }

CodePudding user response:

There is no way in the Firestore API to query across multiple collections with different names. The only options are to query a single collection, or to query all collections with one name using a collection group query.


So you will either have to query each collection (name) individually and merge the results in your application code, or you'll have to adapt your data model to fit the use-case (which is quite common in NoSQL databases).

For example, consider creating a collection inviteCodes where you (also) store the codes using the invite code as the document ID and then include a field that points to the document path for the user (or whatever document type you have) that holds that invite code. Having such a table would not only make this use-case simpler, but it will also immediately ensure that only one user can hold each invite code.

  • Related