StreamBuilder error when data deleted from Firestore - How to catch the error

305 views Asked by At

I am trying to use a stream that listens to updates to a single document but also handles that document being deleted (or not existing until data is entered). However, whenever I delete the firestore document (or before the data is entered), I throw an error saying the method was caught on null. I need to understand how to handle a stream that will have documents updated (works ok in code below) but also deleted (when the error is thrown).

Simply, I am just updating one parameter (lastUpdatedDate = snapshot.data["dateUpdated"];). That's the only code I need from the stream in this example.

Stream used is below: Note that this returns data fine when the document exists.

      Stream<DocumentSnapshot> getLastUpdated(BuildContext context) async* {
final uid = await Provider.of(context).auth.getCurrentUID();
yield* Firestore.instance
    .collection("UserInputDailyAverages")
    .document(uid)
    .collection("Domestic")
    .document(formatDate(DateTime.now(), [yyyy, '', '']))
    .snapshots();

}

This is the builder (again works fine when data is stored in firebase and handles updates no problem:

                       StreamBuilder<DocumentSnapshot>(
                    stream: getLastUpdated(context),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) {
                        return Center(
                          child: CircularProgressIndicator(
                            backgroundColor: kBackgroundColour,
                          ),
                        );
                      }
                      lastUpdatedDate = snapshot.data["dateUpdated"];
                      return SingleChildScrollView(
                        child: Container(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),.....

Then when the document is deleted from firestore, the following error is thrown:

The following NoSuchMethodError was thrown building StreamBuilder(dirty, dependencies: [_LocalizationsScope-[GlobalKey#01484], _InheritedTheme], state: _StreamBuilderBaseState<DocumentSnapshot, AsyncSnapshot>#caa16): The method '[]' was called on null. Receiver: null Tried calling:

I understand that the data can't be read if it doesn't exist but I thought that was being handled by the !snapshot.hasData catch. Any ideas on how to use a stream for data that can be removed from firestore? And how to handle with any additional catch statements? Strangely it seems to think that the snap exists even when it's deleted.

Thanks in advance

0

There are 0 answers