Parallax Effect in Flutter stands for the effect where the direction of an object appears to be different from different positions.
We can implement the same effect in Flutter. So In this blog, we will be implementing the Parallax Effect.
Read more about Flutter app development services by Mobikul
In the Parallax effect, the images seem to be scrolling more slowly than the rest of the screen.
A parallax scrolling effect is achieved by slightly moving the background image in the opposite direction of the rest of the list.
The items slide up the screen, each background image slides slightly downward and vice versa. This results in generating a parallax effect.
In this, we do not need to install any external dependency or plugin, we can directly do so with the help of our code itself.
Integration of Parallax Effect in Flutter
Let’s start the implementation
Here, we will have to create a class that extends FlowDelegate Class and we will also need to
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
class ParallaxFlowDelegate extends FlowDelegate { ParallaxFlowDelegate({ required this.scrollable, required this.listItemContext, required this.backgroundImageKey, }); final ScrollableState scrollable; final BuildContext listItemContext; final GlobalKey backgroundImageKey; @override BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) { return BoxConstraints.tightFor( width: constraints.maxWidth, ); } @override void paintChildren(FlowPaintingContext context) { final scrollableBox = scrollable.context.findRenderObject() as RenderBox; final listItemBox = listItemContext.findRenderObject() as RenderBox; final listItemOffset = listItemBox.localToGlobal( listItemBox.size.centerLeft(Offset.zero), ancestor: scrollableBox); final viewportDimension = scrollable.position.viewportDimension; final scrollFraction = (listItemOffset.dy / viewportDimension).clamp(0.0, 1.0); final verticalAlignment = Alignment(0.0, scrollFraction * 2 - 1); final backgroundSize = (backgroundImageKey.currentContext!.findRenderObject() as RenderBox) .size; final listItemSize = context.size; final childRect = verticalAlignment.inscribe(backgroundSize, Offset.zero & listItemSize); context.paintChild( 0, transform: Transform.translate( offset: Offset(0.0, childRect.top), ).transform, ); } @override bool shouldRepaint(ParallaxFlowDelegate oldDelegate) { return scrollable != oldDelegate.scrollable || listItemContext != oldDelegate.listItemContext || backgroundImageKey != oldDelegate.backgroundImageKey; } } |
We can also add on the Parallax Effect with other widgets like PageView etc.
Conclusion
In this blog, we have discussed integrating the Parallax effect into our Apps.
I hope it will help you understand and get a brief idea about it.
Check out some other Flutter blogs by Mobikul.
Thank you for reading!!
References
https://flutter.dev/docs/cookbook/effects/parallax-scrolling