Create simple 3D button animation with Flutter

Emadeddin Eibo
3 min readApr 4, 2021

--

Flutter has become one of the fastest frameworks to create simple and complex UI components for mobile and web platforms. Even though it has no visual representation of the user interface (like storyboard for iOS), it’s very easy to create and implement beautiful responsive UI and animations.

Today, I’ll show you how to create a simple 3D like animation with Flutter. The output will look like something like this:

First, let’s create an empty project, delete everything and place some text and run:

Okay! Let’s create the button, we’ll create a simple Gesture detector instead of using one of the Flutter pre-made buttons:

The output will look like this:

We still need some shadow under the button to simulate a 3d like effect. The trick here is to use a Stack and position a small Container under our button, we’ll use Positioned Widget to achieve that.

Our code will look like this:

And the output:

Couple things to notice:

  • We needed height: 64 for the Container which is wrapping the Stack, and the difference between it and the actual button height: 60 is the height of the shadow that’s representing the 3D part.
  • The height and width of the shadow must be the same as the actual button, so we can use variables later to simplify our code.

Okay then, animating time!

As we saw earlier, our goal is to move the button down a bit to simulate a 3D press, to do so, we’ll use AnimatedPosition Widget.

The trick is to move the value of the bottom position of the button itself. Keeping the shadow at its place. Here’s the steps needed to do so:

  • Convert to Stateful widget.
  • Wrap the button Container inside an AnimatedPosition widget.
  • Use a double var as the bottom position for the button inside the previous AnimatedPosition widget.
  • Wrap everything inside a GestureDetector widget.
  • Use SetState(){} inside onTap callback in the GestureDetector.
  • Set the position to 0 when calling onTapDown to simulate the animation.
  • Reset the position to its value when finishing the animation (when calling onTapCancel)

We’ll use some vars to set the height and position values, our code will become like this:

And the output will become:

You can add other important stuff like calling the parent widget press call, or providing a specific color for the button or the shadow.

I’ve made this as a library, you can find a detailed and more improved version of it on Github or Pubdev.

Thanks and please share your ideas and improvements notes if you have any ;)

--

--

No responses yet