“This is the 26th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Timer

As for the use of Timer, we can find in iOS that the Timer will conflict with some operations. For example, when sliding a UITableView, the Timer will stop, and you need to switch modes to resolve the conflict. Does the Timer in Flutter have the same problem?

In the list interface, we add a Timer with the following code:

We add a Timer to our initState method that executes every second, incrementing _count by 1, and destroying the Timer when _count is 99. Cancel ();

Let’s look at the effect of the sliding list while the timer is running:

The Timer does not affect the slide operation of the list in Flutter. Sliding lists are not affected by timers;

Timer memory leak problem

Although the Timer in the Flutter does not conflict with the slide of the list, we still have problems using this method. See the following operation:

After we cut out the page, the timer is not completely destroyed. At this time, when our page is in the reserved state, if we choose not to retain the state, the following situation will occur:

It can be seen that when the page is wantKeepAlive = false, if the interface is switched, two timers will exist at the same time when the page is switched back again. So how to solve it?

At this point, we need to dispose, another function in the Widget lifecycle;

Dispose method of Widget

Dispose method is similar to dealloc method in iOS, which will be called after we switch pages. You can do some object destruction in this method. We need to dispose method to release the Timer, the code is as follows:

Before destroying Timer in dispose method, you need to determine whether _timer is empty and whether it is out of execution state.

In this case, if we wantKeepAlive = false, the Timer will be destroyed every time the page is switched out and a new Timer will be created after the page is returned. If wantKeepAlive = true, dispose will not execute or destroy the Timer after the page is switched out because the state is retained. When the page appears again, the second Timer will not be created.