'StreamSubscription as global variable does not cancel events as it should

i have global StreamSubscription variable outside the stfl widgetlike following

StreamSubscription<QuerySnapshot<Map<String, dynamic>>>? message;

class Messages extends StatefulWidget {
  const Messages({Key? key,}) : super(key: key);
  @override
  _MessagesState createState() => _MessagesState();
}

class _MessagesState extends State<Messages> {

 @override
  void initState() {
    super.initState();
    listen();
  }

Future listen()async{
 messgse =   FirebaseFirestore.instance.collection("messages").
      limit(20).orderBy("timestamp",descending: true).snapshots().listen((dodo)async {
       //events actions 
   });
}

@override
  Widget build(BuildContext context) {
   return(..)
}
}

well , as my need i can't use StreamSubscription variable as local because i need events keep flowing .

now i am using .cancel() once user sign-out . it is cancel BUT not in all cases , i noticed that after calling .cancel()events run again after some moments

signOut(){
FirebaseAuth.instance.signOut();
 Navigator.of(context).pushAndRemoveUntil(
 FromDown(child: const EntryPage()), // here i go to another `Stfu` and events stopped for some moments then worlk again it's self if there is changes in firstore   
 (rout)=>false
  );
messgse.cancel(); // Although I cancel it 
}

but if i used StreamSubscription as local then i cancel it using dispose function so it will completely cancel the StreamSubscription as wanted like following

class Messages extends StatefulWidget {
  const Messages({Key? key,}) : super(key: key);
  @override
  _MessagesState createState() => _MessagesState();
}
class _MessagesState extends State<Messages> {
 StreamSubscription<QuerySnapshot<Map<String, dynamic>>>? message;// as local will completely  cancel
      @override
      void dispose() {
        super.dispose();
        message!.cancel(); // here will completely  cancel
      }
}
}

My question is Why if i used it as global it does not completely cancel , where is the difference ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source