Jiwa Chhetri
Jiwa Chhetri

Reputation: 109

How to rerender a widget without recreating the widget - flutter / dart

In the code below. There are two CountdownTimer ( yellow and red) and when the condition is changed, the CountdownTimer widget which is shown on the display will change, i.e switch from yellow to red and vice versa.

However, when it switches, the CountdownTimer becomes "reinitialized". For instance, say the initial timer for the yellow is 60 seconds and after ticking for 40 seconds, it's down to 20 seconds left. At this moment, the condition is changed twice, say for 5 seconds, thus CountdownTimer switches to red and back to yellow. Instead of carrying on a timer from 15 seconds, it restarts from 60 seconds. How do I prevent this "reinitialization" of the widget and allow the timer to carry on independent on the background, regardless of the condition?

Also, to make this question easier to understand, I have used an adapted version of the code. Therefore, in the real code, I cannot use a variable to store the value of endTime. So, another version of the answers will be required.

In essence, I need a way to keep both CountdownTimer alive in the background without the flutter garbage collect from deleting it.

condition ? CountdownTimer( // yellow
                    endTime: DateTime.now().millisecondsSinceEpoch + 200000,
                    textStyle: TextStyle(fontSize: 50, color: Colors.yellow),
                  )
: CountdownTimer( // red
                    endTime: DateTime.now().millisecondsSinceEpoch + 1000,
                    textStyle: TextStyle(fontSize: 50, color: Colors.red),
                  ),

Thank you for taking the time to read this.

Upvotes: 1

Views: 650

Answers (1)

Ridcully
Ridcully

Reputation: 23655

Can you not have both timers at all times and just change the visibility depending on the condition?

Also see this: https://stackoverflow.com/questions/44489804/show-hide-widgets-in-flutter-programmatically#:~:text=Flutter%20now%20contains%20a%20Visibility,gone%20and%20a%20lot%20more.

Upvotes: 2

Related Questions