Flutter firebase: Bad state: field does not exist within the DocumentSnapshotPlatform

Viewed 50

I'm getting this error:

Bad state: field does not exist within the DocumentSnapshotPlatform

with the following code:

static List<Report?> reportListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map<Report?>((report) {
      return Report(
        type: report['type'],
        reason: report['reason'],
        reportId: report['id'],
        chat:
            (report['chat'] == null) ? null : Chat.chatFromMap(report['chat']),
        stingray: Stingray.stingrayFromDynamic(report['stingray']),
        reporterUser: User.fromDynamic(report['reporterUser']),
        reportTime: report['reportTime'].toDate(),
      );
    }).toList();
  }

Its failing on the first map,

type: report['type'],

and when i look at it in debug mode, it shows the data i am looking for: enter image description here

As you can see from the screenshot, 'type' exists with a value of 'chat report'. Any idea why this is breaking? Thanks!

2 Answers

You are supposed to call .data() on report

static List<Report> reportListFromSnapshot(QuerySnapshot snapshot) {
  final List<Report> reports = [];
  for (final doc in snapshot.docs) {
    final report = doc.data() as Map<String, dynamic>?; // you missed this line.
    if (report == null) continue;
    reports.push(
      Report(
        type: report['type'] as String,
        reason: report['reason'] as String,
        reportId: report['id'] as String,
        chat: (report['chat'] == null)
            ? null
            : Chat.chatFromMap(report['chat']),
        stingray: Stingray.stingrayFromDynamic(report['stingray']),
        reporterUser: User.fromDynamic(report['reporterUser']),
        reportTime: (report['reportTime'] as Timestamp).toDate(),
      ),
    );
  }
  return reports;
}
// I returned List<Report> not List<Report?>

Check out this link on how to use withConverter so you do not have to manually convert models.

The problem turned out to be larger in scope than i thought. I was uploading a map object to firebase rather than just a document, and that map was attempting to be read, which is where the error occurred due to it only having one value in the document snapshot.

Related