Welcome to the world of Flutter! Flutter, one of the fastest-growing mobile app development frameworks, has silently revolutionized how developers perceive and work with UI frameworks. But to genuinely appreciate the magic of Flutter, we need to understand the unsung heroes, such as the Flutter ticker.
The Flutter ticker is the key part of the Flutter magic. It is the orchestrator that ensures the smooth execution of animations, the seamless transitions, and the "fluid motion" of the UI, making it visually appealing and satisfying to the human eyes.
A ticker, in simple terms, is a time tracker. It is responsible for recording the elapsed duration since the animation started. It signals its callbacks about the duration elapsed and hurries to set up the next scheduled frame, making sure that the transitions on the screen are played at "such a fast" rate that it gives a smooth, continuous recording to our human eyes.
Good Flutter UIs will usually include animations making the application lively and a joy to use. When we talk about these intricate animations, the concept of a 'frame' becomes significant. Ever watched a cartoon? It's just an arrangement of multiple images displayed at such a fast rate giving an illusion of one continuous recording. That's essentially the principle behind animations on any UI screen.
In Flutter, every new frame of your app is displayed at an arbitrary period value. If your app's UI changes over time or due to some event, this change is held off until the next frame.
So, the change essentially happens at the next render of the UI, thus giving an instant or immediate reflection on the user's screen. How frequently these new frames are issued depends on the device's refresh rate, often 60 frames per second.
The Ticker Provider in Flutter is an interface for classes that can vend Ticker objects. It might sound technical, but simply put, Tickers in Flutter are scheduled to tick on every frame when started, via the scheduleFrame function. Once the actual animation taking place comes to a halt or gets paused, the tickers are consequently muted too!
Managing when to start ticking and when to mute is the role of the Ticker Provider and its subclasses like SingleTickerProviderStateMixin and TickerProviderStateMixin. Mutual animations supported by the same object, also known as the ticker provider, are held off when they're not displaying anything, thus saving your resources.
1 class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { 2 AnimationController _controller; 3 4 @override 5 void initState() { 6 super.initState(); 7 _controller = AnimationController( 8 vsync: this, 9 duration: const Duration(seconds: 5), 10 )..repeat(reverse: true); 11 } 12 // Rest of the code 13
Now that we've got the theoretical aspects of a Flutter ticker out of the way, and you understand the "frame" concept, too, let's dive into some practical examples, because a Flutter ticker example speaks a thousand words.
Consider a simple scenario where we want to animate a Flutter widget, such as a button growing in size over a certain duration. We would need a ticker for tracking the elapsed time for the animation.
1 Ticker ticker; 2 double size = 1; 3 4 startAnimation() { 5 ticker = Ticker((elapsed) { 6 setState(() { 7 size = size + elapsed.inMicroseconds / Duration.microsecondsPerSecond; 8 }); 9 }); 10 ticker.start(); 11 } 12 13 //Inside build function 14 AnimatedContainer( 15 duration: Duration(seconds: 2), 16 curve: Curves.bounceInOut, 17 width: 100 * size, 18 height: 100 * size, 19 color: Colors.blue, 20 ) 21
Can you see how the size of the button is changing with the elapsed duration? It's Flutter's ticker performing its magic! Every time a new frame appears, the Flutter engine ticks, increasing the size set in setState.
In the above example, the ticker starts, and with each elapsed duration, the size of the button increases. The build context is set again, resulting in the Flutter widget on the screen growing in size.
As with everything else in Flutter, using the Flutter Ticker API is mostly smooth sailing. However, like any UI framework, there could be instances when you encounter difficulties. One of the most common issues arises from not properly handling the lifecycle of a ticker in Flutter.
Upon creation, a ticker starts in the muted state (does not call its callback) and stays that way until it's started. Once started, it calls back periodically until stopped or disposed of. If a ticker was disposed while it was active, it will immediately stop ticking.
So how do we resolve these minor hitches when they arise?
Understanding the way tickers work, you should always remember 3 things:
1 class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { 2 Ticker _ticker; 3 double _size = 1; 4 5 @override 6 void initState() { 7 super.initState(); 8 _ticker = Ticker(_tick); 9 } 10 11 void _tick(Duration elapsed) { 12 setState(() { 13 _size = _size + elapsed.inMicroseconds / Duration.microsecondsPerSecond; 14 }); 15 } 16 17 @override 18 void dispose() { 19 _ticker?.dispose(); 20 super.dispose(); 21 } 22 23 // Rest of the code 24
With the lifecycle of the ticker managed correctly, your Flutter entertainment journey will be much smoother.
While Flutter tickers seem relatively straightforward, they hold great power and flexibility. Understanding their full use case and capabilities can significantly optimize Flutter animations.
Remember, while animations are fun and engaging, too many animations or unoptimized animations could use unnecessary resources, thus affecting your application's performance.
Even though it seems like Flutter animations are continuously playing and ticking, each animation only updates and calls setState during a frame. This process ensures Flutter only rebuilds the widget tree during a frame, thus maintaining the "60 frames" per second rule, always satisfying human eyes.
1 TickerProvider provider = TickerProvider(); 2 AnimationController controller = 3 AnimationController(vsync: provider, duration: Duration(seconds: 2)); 4 5 controller.addListener(() { 6 if (controller.status == AnimationStatus.completed) { 7 controller.reverse(); 8 } 9 }); 10 11 controller.addStatusListener((status) { 12 if (status == AnimationStatus.dismissed) { 13 controller.forward(); 14 } 15 }); 16
With this, we complete a detailed walkthrough of the Flutter ticker and its associated roles. Keeping these concepts in your toolkit will help you get the optimal use of Flutter animations.
And there you have it - our detailed journey through understanding Flutter's ticker wrapped up! Who would've thought that this subtle and lesser-known aspect of Flutter could contain such complexities and underpin so many essential functionalities, notably Flutter animations.
With the knowledge shared in this blog post, not only will you better understand the underlying UI framework and the maintenance of the 'new frame' rate, but you will also be able to efficiently leverage Flutter tickers in your Flutter applications. However, don't stop here.
Flutter offers a robust, versatile, and performant framework for creating beautiful applications that only continue to get better!
So, now as you step back into your Flutter journey, remember - the magic of ticking, the science behind each new frame, and the periodic tickers bringing your Flutter widget to life - it's all just the Flutter Ticker API at play! Just like how 'the boy changes position in several frames, creating an animation', your understanding of Flutter and its inner workings has now moved several frames forward, bringing you closer to mastering the art of Flutter!
Go on and continue to create awesome animations and engage your users like never before. Flutter your way to success!
That brings us to the end of our journey. Happy fluttering, and may your tickers always remain unhindered!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.