The overlay is a Stack of entities that can be controlled independently. We need it if we want to overlay a widget on top of the screen, but we don’t want to overlay a widget already on the screen. This article will take a closer look at how you make an animated FAB with a dropdown list using an Overlay widget.
First, we create a standard Flutter project with a StatefullWidget and a MaterialApp that makes a Navigator, inside which we create an Overlay.
To create AnimationController, let’s add SingleTickerProviderStateMixin mixin (if you want to make a few AnimationControllers, then TickerProviderStateMixin should be used).
Next, we create a controller and a list of animations for all the items in the dropdown list.
Now they need to be initialized.
To make the animation of the icons more beautiful, we use CurvedAnimation, adding an interval and a curve.
Then we create some buttons in our Scaffold body and wrap them in ScaleTransition, which will make the animation of the buttons zooming in.
When we click on the main FAB, we will trigger our animation:
As a result, we have three buttons appearing smoothly when we click the button.
But we want them to appear on top of the main Menu FAB, and to do this. We will use the Overlay widget.
First, we create an OverlayEntry and put our buttons in a separate method showOverlay ().
In the body of the OverlayEntry method, let’s declare OverlayEntry and put our buttons in the builder of this widget.
The next step is to insert our OverlayEntry into OverlayState by the insert () method.
Let’s add a listener and start the animation.
Now let’s assign this method to our main FAB.
Every time you click on the button, we will create an Overlay.
But we still haven’t reached our main goal: to make the buttons appear on top of our main FAB.
This is where the fun part starts.
How do we know where to put our elements?
We have to get the RenderBox of our button to get the position, size, and other information about the widget.
To do that, we create a global key and assign it to our FAB.
To get the RenderBox of our main button, we need to call the findRenderObject() global key method.
Then call the local to the global method of the RenderBox object, which is designed to determine the widget’s coordinates on the screen. Send to it Offset.zero, means we take (0,0) coordinates inside this render box and convert them to the corresponding coordinates on the screen.
Let’s wrap our Column with buttons in Positioned (this widget is used for positioning in Stack, Overlay is what it is). And let’s set its position thanks to the Offset we got. On the left side, we set the same position as the main button, and at the bottom, we add to the height of the render box a small indent.
Let’s add a delay to the showOverlay method.
As a result, we’ve got what we want — an animated overlay:
Link to source code: https://github.com/klyovan/animated_overlay