Home > database >  StateError (Bad state: field does not exist within the DocumentSnapshotPlatform). How can I get a do
StateError (Bad state: field does not exist within the DocumentSnapshotPlatform). How can I get a do

Time:12-01

I'm new to flutter. I want to get a specific doc from firestore using its uid and then transfer this doc in a value type that I can handle. BUT i get a breakpoint when I run my application : StateError (Bad state: field does not exist within the DocumentSnapshotPlatform). This the code:

final cloth = await DatabaseService(uid: uid)
          .clothCollection
          .doc(uid)
          .get()
          .then((doc) => {
                            Cloth(
                    brand: doc.get('brand'),
                    name: doc.get('name'),
                    color: doc.get('color'),
                    url: doc.get('url'))
              });

and Cloth :

class Cloth {
  final String? name;
  final String? url;
  final String? brand;
  final String? color;

  Cloth({this.name, this.brand, this.color, this.url});
}

If there is an easier way to get this doc let me know. Thanks for your help!

CodePudding user response:

The get attribute does not exist on the DocumentSnapshot(doc). Instead, you have to use the data() method which returns a Map<String, dynamic>, or null if the doc does not exist. It's good practice to always check to see if the document exists first before executing further.

final cloth = await DatabaseService(uid: uid)
          .clothCollection
          .doc(uid)
          .get()
          .then((doc) {
            if (doc.exists) {
            Map<String, dynamic>? data = doc.data();

              return Cloth(
                    brand: data?['brand'],
                    name: data?['name'],
                    color: data?['color'],
                    url: data?['url']);
           } else {
              print('Document does not exist.');
            }
              });
  • Related