Home > Software engineering >  Flutter firestore database returns null
Flutter firestore database returns null

Time:01-16

I have following code:

DebugImage

I use cloud firestore as database

Database

UserModel:

class DbUser {
  String id;
  final String authUserID;
  final String userName;
  final List<String>? itemsForSale;
  final List<String>? itemFavourites;
  final List<String>? bids;

  DbUser(
      {this.id = '',
      required this.authUserID,
      required this.userName,
      this.itemsForSale,
      this.itemFavourites,
      this.bids});

  Map<String, dynamic> toJson() => {
        'id': id,
        'authUserID': authUserID,
        'userName': userName,
        'itemsForSale': itemsForSale,
        'itemFavourites': itemFavourites,
        'bids': bids,
      };

  static DbUser fromJson(Map<String, dynamic> json) => DbUser(
        id: json['id'],
        authUserID: json['authUserID'],
        userName: json['userName'],
        itemsForSale: json['itemsForSale'] is Iterable
            ? List.from(json['itemsForSale'])
            : null,
        itemFavourites: json['itemFavourites'] is Iterable
            ? List.from(json['itemFavourites'])
            : null,
        bids: json['bids'] is Iterable ? List.from(json['bids']) : null,
      );
}

Repository class

  final _firestoreDB = FirebaseFirestore.instance;



  Future<DbUser?> getDBUserByDBUserId({required String dbUserID}) async {
    final docUser = _firestoreDB.collection('users').doc(dbUserID);
    final snapshot = await docUser.get();

    if (snapshot.exists) {
      return DbUser.fromJson(snapshot.data()!);
    }

    return null;
  }

snapshot.exists returns false. I do not understand why? my snapshot returns null but I do not see why it does that, could somebody please help me?

Thank you

CodePudding user response:

Space

found my problem, there was a space before my Id that had been retreived, I must have accedentally put it there when creating the database...

CodePudding user response:

Looking at the screenshot of the document you shared, the document ID in the second column is different from the value of authUserID in the third column. So it seems like you added the document by calling add, which means that Firestore generates a unique ID for you.

You then create a reference to the document with this code:

_firestoreDB.collection('users').doc(dbUserID)

But here you are specifying dbUserID as the document ID, which doesn't match what you did when you created the document. Firestore now looks for a document with an ID that is the same as the user ID, which doesn't exist and thus gives you a snapshot where exists is false.

If you want to find the document for the user in your current structure, you can use a query to do so:

Future<DbUser?> getDBUserByDBUserId({required String dbUserID}) async {
  final query = _firestoreDB.collection('users').where('authUserID', isEqualTo: dbUserID)

  final snapshot = await query.get();

  if (snapshot.size > 0) {
    return DbUser.fromJson(snapshot.docs[0]!.data()!);
  }

  return null;
}

But a better solution might be to actually store the user document under its user ID. You can specify the document ID as shown in the documentation on setting a document. So here you'd call .document('theuserid').set(...) instead of add(...).

  • Related