Create A Simple Animated FloatingActionButton in Flutter
Hi there,
This post will cover the steps of how to create a simple animated FloatingActionButton (FAB) in Flutter. I tell you that this might be not the best approach. But I hope it will be helpful.
For you who hasn’t known about what FAB is, please check this link.
Getting Started
Flutter comes with a starter kit that displays the following:
Do you see the button in bottom right? It’s what we call a FloatingActionButton (FOB). In the above picture, what it does is simply increment the counter that displayed in the center of the screen. Is it sounds boring? Let’s do some experiments then.
Create Custom Widget
As usual, we should make separated file for custom widget. So our project’s structure will be more organized. Now, create a file named fancy_fab.dart:
The result is like the following:
Yosh! You see that the button morphs between icons. This is achieved by using AnimatedIcon
widget. But that won’t stop us to do more. Let’s add more buttons. Instead of return a single toggle(), we return a Column that contains buttons as its children:
The updated result:
Now there are 3 more buttons. We can see that the toggle button still performing. But nothing happens to the other buttons. I’m thinking of showing/hiding them according to the toggle button. So, for the default initiation, we have to set those buttons’ position to be behind the toggle button. For this scenario, we can make use of Transform
widget. Let’s do that:
The last result:
To use this custom widget, you can use it in your Scaffold
's floatingActionButton
for the best practice. But it also works anywhere in the tree.
Conclusion
Flutter widget is very powerful and flexible. We can create a silky smooth animation without having to worry about the perfomance.
Again, I tell you that this not the best approach to achieve this kind of animation. You can even create the better approach than mine. But at least, this post lets you know the basic idea of how to customize the floating action button.