I'm new to Dart/Flutter and would like to build a simple app where a LinearProgressBar gets updated every second.
Without getting too much into the actual code, I have the following setup working.
Everything is working as expected with one exception. The 'tick' keeps getting printed when I move the app in the background on my Android device.
On native Android, I would cancel my periodic Timer when the 'onPause' event is triggered.
Is there something similar in Flutter? All I could find was 'initState' and 'dispose'. Dispose, however, does not get called when moving the app to background.
I don't want the timer to keep ticking in the background.
On my research, I found this Stack Overflow question onresume-and-onpause-for-widgets-on-flutter. It's answer suggests using TickerProviderStateMixin.
I used it the following way.
class _BarItemState extends State<BarItem> with SingleTickerProviderStateMixin {
Ticker ticker;
num progress = 1.0;
@override
void initState() {
super.initState();
ticker = createTicker((duration) => setState(() {
debugPrint('tick');
progress = duration.inSeconds / 30;
}))
..start();
}
// other stuff omitted
}
It is working, but I'm still not satisfied.
The reason is, that the ticker callback is getting now called every few milliseconds instead of once a second. This seems to me like a waste of resources (I don't need a smooth animation), ... am I overcomplicating things?
Even if it seems that I don't need it for my use case, I still would like to know:
How to handle the onPause/onResume events on my own?
The lifecycle of the Flutter App is the show of how the application will change its State. It helps in understanding the idea driving the smooth progression of our applications. Everything in Flutter is a Widget, so before thinking about Lifecycle, we should think about Widgets in Flutter.
State objects have the following lifecycle: The framework creates a State object by calling StatefulWidget. createState. The newly created State object is associated with a BuildContext.
You can override the didChangeAppLifecycleState
of the WidgetBindingObserver
interface to receive notifications for app lifecycle changes.
There's sample code in this page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With