简体   繁体   中英

Flutter Firestore - NoSuchMethodError: The method '[]' was called on null

Okay. I've been using Flutter for a little more than a year now. I've been using this same code in almost every app, and it works. For some reason, it doesn't work in this new app that I'm building.

String testString(DocumentSnapshot doc, String val) {
  try {
    if (doc == null) {
      return "error! DB not found!";
    }
    if (doc[val] == null) {
      return "'" + val + "' doesn't exist in DB";
    }
    return doc[val];
  } catch (e) {
    return "Error: something went wrong";
  }
}

I've also tried this:

String testUndString(DocumentSnapshot doc, String val) {
  try {
    return doc != null ? (doc[val] != null ?  doc[val] : "undefined") :  "undefined";
  } catch (e) {
    return "Error: something went wrong";
  }
}

and this:

String testUndString(DocumentSnapshot doc, String val) {
  try {
    return doc.data != null ? (doc[val] != null ?  doc[val] : "undefined") :  "undefined";
  } catch (e) {
    return "Error: something went wrong";
  }
}

After doing some searching, it looks like I've done this correctly, but it still returns the error:

NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.)

Try this code:

if (doc is !DocumentSnapshot) {
    return "error! DB not found!";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM