Home > Mobile >  Flutter Future.delayed timer dispose when navigating to other page
Flutter Future.delayed timer dispose when navigating to other page

Time:07-01

In my flutter app, I have a function that has delaye for 5 seconds to activate a button. When I navigate to other page, the timer of the delayed is still working even though I use the "pushReplacement" navigator. Can anyone help me find a way to dispose or cancel this timer when I navigate to other page.

here is the code:

 Future sendVerificationEmail() async {
  try{
    final user =FirebaseAuth.instance.currentUser!;
    await user.sendEmailVerification();

    setState(() => canResendEmail = false);
    await Future.delayed(const Duration(seconds: 5)); // this is the line causing the error
    setState(() => canResendEmail = true);

  }catch (e) {
    Utils.showSnackBar(e.toString());
  }
  }

and here is the navigation button function:

Future<void> SignOut() async {
   await FirebaseAuth.instance.signOut();
   Navigator.pushReplacement(
     context,MaterialPageRoute(builder: (context) =>  mainPage()),

   );
 }

CodePudding user response:

Try using a timer instead

Timer timer = Timer(Duration(seconds: 5), () {
    //do something here();
  });
  // You can dispose the timer like this
  timer.cancel();

  • Related