Spike: Parallax in Flutter, seven lines of code!

Swav Kulinski
2 min readApr 24, 2018

--

It always goes like this. Designer sends you an invite to Zeplin. You look at the designs, they are nice clean and polished. The main layout looks so cool. You skim through other screens to get the glimpse of the UX flow. Now you build the image of the app in your head and suddenly you come to a realisation — each of these nice animations between different states will take a couple of days to develop. Testing it will take a bit longer because of supported system versions. Nice design, shame most of it will end up in a backlog neverland.

Flutter was designed to allow us to avoid compromise on UX while keeping code size to a bare minimum. Promises are carved on the tombstones of all abandoned technologies — simple, reusable, easy to scale. Hearing so much about how simple it is to build brilliant UI in Flutter I’ve decided to put this claim to the test.

How much code do we need?

Here is the layout. Simple CustomScrollView with cards. Beneath it, there is an image we want to slowly move as our scroll view moves.

The interesting part is where we composite our layout from two independent layers in one Stack widget.

First step will be to add a property to the State that will tell us what is the current top position of the background image.

var top = 0.0;

Then we set this variable to Positioned widget.

new Positioned {
top : top,
...

Now the fun part is to add NotificationListener widget on top of the hierarchy and make its onNotification handler set the top property

return new Scaffold {
body: new NotificationListener(
onNotification: (v) { if (v is ScrollUpdateNotification) {
setState(() => top -= v.scrollDelta/2);
}
},
child :
new Stack (
...
),
),
}

And that’s about it. Positioned widget will now move with half of the speed CustomScrollView is moving.

Where is the magic?

CustomScrollView will bubble up the events to its parents. If there is a NotificationListener up there it will intercept the notification and make use of it. Here is the entire State class.

Here is the video of how it behaves on a device.

I hope you’ve enjoyed this little sample and now you have brilliant ideas of how to use it in your layouts.

Flutter allows creating widgets that listen to each other in a simple and intuitive way. It is a result of effective use of the composition. Dividing widgets into ones that look, ones that position their children on the screen, and ones which control behavior creates limitless possibilities for the designer and developer. Unlocking this potential by working closely with designers should be our priority.

--

--

Swav Kulinski

Computer enthusiast since 80s, Android developer since Eclair, now Flutter enthusiast. https://gitlab.com/swav-kulinski