Eradicatore
Eradicatore

Reputation: 1629

Is there a way to set a periodic timer for a Flutter StatefulBuilder to update with setState() every 1 second?

I found this help on StatefulBuilder and it shows how to use setState to update things in a ModalBottomSheet. But I want to go one more step and make a timer to do this.

https://stackoverflow.com/a/56972160/559525

I create the timer like this inside the stateful builder:

var bottomSheetTimer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
  setState(() {
    currSeekTime += 1;
    print("here");
  });
});

This prints out every second but the setState() isn't within the "builder" so nothing in the bottom tab updates. But if I put it in the builder it creates a LOT of timers.

Any help would be appreciated!

Upvotes: -1

Views: 706

Answers (2)

Rohan KP
Rohan KP

Reputation: 1

Yes there is but you are better off making a separate widget and doing things on onInit etc instead of build.

In this case needed to add a delay to a button before its enabled on the dialog since the component was stateless instead of creating a new widget , manged it like so temporarily

The trick is to only create a new timer in the builder if its not null. This prevents creating extra timers on each build and memory leaks

 int timeout = 5;
  Timer? timer;
  Get.dialog(StatefulBuilder(builder: (context, StateSetter setState) {
    timer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timeout <= 0) {
        timer.cancel();
      } else {
        timeout--;
      }
      setState(() {});
    });
    return ConfirmationDialog(
        title: LanguageConst.confirmText,
        confirmText: timeout == 0
            ? LanguageConst.deleteAccount
            : "${LanguageConst.wait} ${timeout}s",
        confirmEnabled: timeout == 0,
        cancelText: LanguageConst.cancelText,
        content: LanguageConst.areYouSureYouWantToDeleteProfile,
        onConfirm: deleteAccountAction,
        onCancel: () {
          Get.back();
          timer?.cancel();
        });
  })).then((value) => timer?.cancel());

Upvotes: 0

Lee3
Lee3

Reputation: 3077

The correct approach would be to create the Timer in the initState method, not build.

Upvotes: 0

Related Questions