When I try to cancel a Firestore listener with
ProductsService().cancel(). I get the error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: LateInitializationError: Field 'productsSubscription' has not been initialized.
Without late also doesn't work:
StreamSubscription<QuerySnapshot>? productsSubscription;
My code:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class ProductsService extends ChangeNotifier {
late StreamSubscription<QuerySnapshot> productsSubscription;
void cancel() => productsSubscription.cancel();
void getMenuProducts() async {
CollectionReference productsReference = FirebaseFirestore.instance.collection('products');
productsSubscription = productsReference.snapshots().listen((snapshot) => print(snapshot.docs.length));
}
}
I know calling .cancel() on it works inside a context. But I am using this in a ChangeNotifier with Riverpod.
The stream with Riverpod works fine. The real issue is that when the user logs out and a new user logs in, the .listen still seems to be stuck on the old firebase user! and doesn't allow queries. Firebase rules reject them with [cloud_firestore/permission-denied] - and when I restart the app the query works.
What I noticed is that If I can get the .listen canceled at the time of logging out, the query works when the new user logs in.
So if anyone can help me initialise this properly, or get Firebase to see the new user, it would help very much. Or any other suggestions.