How can i dispose or close a listen function from Firestore?

467
Stream<QuerySnapshot<Map<String, dynamic>>> myStream = FirebaseFirestore.instance.collection("handleCountM").limit(1).snapshots();

late StreamSubscription<QuerySnapshot<Map<String, dynamic>>> streamSubscription;
  

void handleDelete() {
    streamSubscription = myStream.listen((value) {
      value.docs.forEach((element) {
        element.reference.delete();
      });
    });
  }


  @override
  void dispose() {
    streamSubscription.cancel(); //Cancel your subscription here.
    super.dispose();
  }

Your other alternative, would be to use a streambuilder, and it'll handle the subscription and termination for you.

Share:
467
Jack
Author by

Jack

Updated on December 17, 2022

Comments

  • Jack
    Jack over 1 year

    Flutter

    i have this listen function into stful which i need to close it when press on the back button

        class Test extends StatefulWidget {
          const Test({Key key}) : super(key: key);
        
          @override
          _TestState createState() => _TestState();
        }
        
        class _TestState extends State<Test> {
        
          handleDelete(){
        
            FirebaseFirestore.instance.collection("handleCountM").limit(1).snapshots().listen((value) {
              value.docs.forEach((element) {
                element.reference.delete();
              });
            });
    
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    

    i have no idea how could i stop it into dispose()

  • Jack
    Jack almost 3 years
    thanks a lot huthaifa but i don't use null safety version what should i use instead late?
  • Huthaifa Muayyad
    Huthaifa Muayyad almost 3 years
    Just remove the word late.
  • Huthaifa Muayyad
    Huthaifa Muayyad almost 3 years
    And read about null safety and start using it :) Lot's of work by the team was put into it, for many very good reasons, which are worth diving into :)