SlideTransition Widget - Flutter Widget Guide By Flutter Agency

SlideTransition Widget – Flutter Widget Guide By Flutter Agency

SlideTransition Widget in Flutter is a widget that animates the position of a widget relative to its normal position.

The translation is expressed as an Offset scaled to the child’s size.

For example, an Offset with a dx of 0.25 will result in a horizontal translation of one-quarter of the width of the child.

By default, the offsets are applied in the coordinate system of the canvas. If a textDirection is provided, then the offsets are applied in the reading direction, So in the right-to-left text, positive x offsets move towards the left, and in left-to-right text, positive x offsets move towards the right.

Default Constructor for it will look like below:

SlideTransition({
  Key? key,
  required Animation position,
  bool transformHitTests = true,
  TextDirection? textDirection,
  Widget? child,
})

In Above Constructor all fields marked with @required must not be empty. We will understand every property step by step.

Properties:

  • Key: This attribute key controls how one widget replaces another widget in the tree.
  • Animation<Offset> position: This attribute is used to define the animation that controls the position of the child. If the current value of the position animation is (dx, dy), the child will be translated horizontally by width * dx and vertically by height * dy, after applying the textDirection if available.
  • bool transformHitTests: This attribute defines whether hit testing should be affected by the slide animation. If false, hit testing will proceed as if the child was not translated at all. Setting this value to false is useful for fast animations where you expect the user to commonly interact with the child widget in its final location and you want the user to benefit from “muscle memory”.
  • TextDirection textDirection:  This attribute will define the direction to use for the x offset described by the position. If textDirection is null, the x offset is applied in the coordinate system of the canvas so positive x offsets move the child towards the right. Now if textDirection is TextDirection.rtl, the x offset is applied in the reading direction such that x offsets move the child towards the left. So now, if textDirection is TextDirection.ltr, the x offset is applied in the reading direction such that x offsets move the child towards the right.
  • Widget child: This attribute is used to define the widget below this widget in the tree. This widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row WidgetColumn Widget, or Stack Widget, which have a children’s property, and then provide the children to that widget.

How to use SlideTransition Widget in Flutter?

The following code snippet tells us how to implement SlideTransition Widget in Flutter.

The user needs to define the controller and animation using the below code snippet.

late AnimationController _controller;
late Animation _animation;

initState() will have a code snippet as below:

@override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    )..forward();
    _animation = Tween(
      begin: const Offset(-0.5, 0.0),
      end: const Offset(0.5, 0.0),
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInCubic,
    ));
  }

The scaffold body will return a Builder() like below:

Builder(
        builder: (context) => Center(
          child: SlideTransition(
            position: _animation,
            transformHitTests: true,
            textDirection: TextDirection.ltr,
            child: ElevatedButton(
              child: const Text('SlideTransition'),
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Button is pressed'),
                  ),
                );
              },
            ),
          ),
        ),
      ),

So now our complete code snippet will look like below:

import 'package:flutter/material.dart';

class SlideTransitionWidget extends StatefulWidget {
  const SlideTransitionWidget({super.key});

  @override
  _SlideTransitionWidgetState createState() => _SlideTransitionWidgetState();
}

class _SlideTransitionWidgetState extends State
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _animation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    )..forward();
    _animation = Tween(
      begin: const Offset(-0.5, 0.0),
      end: const Offset(0.5, 0.0),
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInCubic,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (context) => Center(
          child: SlideTransition(
            position: _animation,
            transformHitTests: true,
            textDirection: TextDirection.ltr,
            child: ElevatedButton(
              child: const Text('SlideTransition'),
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Button is pressed'),
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

We will get output like below.

slideTransition Widget

General Queries on SlideTransition Widget

  • My app is a simple Column Widget with 3 Text Widget wrapped in SlideTransitions.
  • My goal is for the app to load with nothing on the screen, and then animate these Text Widget from the bottom (off-screen) up into the screen.
  • The current code Snippet will look like below:
    Column(
            children: [
              SlideTransition(
                position: _curve1,
                child: const Text('Hello 1'),
              ),
              SlideTransition(
                position: _curve1,
                child: const Text('Hello 2'),
              ),
              SlideTransition(
                position: _curve1,
                child: const Text('Hello 3'),
              ),
            ],
          ),
    

    initState() will look like below:

     late AnimationController _animationController;
      late Animation _curve1;
    
      @override
      void initState() {
        _animationController = AnimationController(
          duration: const Duration(seconds: 3),
          vsync: this,
        )..forward();
        Offset beginningOffset = Offset(0.0, 20.0);
        _curve1 = Tween(begin: beginningOffset, end: Offset.zero).animate(
          CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
        );
      }
    

Answer:

Users might want to try using the addPostFrameCallback method in your initState().

@override
   void initState() {
     super.initState();
     WidgetsBinding.instance.addPostFrameCallback((_){
        // Schedule code execution once after the frame has rendered
        print(MediaQuery.of(context).size.toString());
     });
   }

Or Users can also use a Future for this:

@override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      // Schedule a zero-delay future to be executed
      print(MediaQuery.of(context).size.toString());
    });
  }
  • Flutter slideTransition is not animating?

I’m trying to create a trivial slide transition element in flutter and I’m having some difficulty.

What the below does is wait for the animation time, and then just display the Text(“hello there sailor”). I don’t know why this is not animating.

import 'package:flutter/material.dart';

class DeleteCheck extends StatefulWidget {
  const DeleteCheck({
    super.key,
    this.offsetBool,
    required this.widthSlide,
  });
  final offsetBool;
  final double widthSlide;
  @override
  State createState() => _DeleteCheckState();
}

class _DeleteCheckState extends State
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _offsetFloat;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );

    _offsetFloat =
        Tween(begin: Offset(widget.widthSlide, 0.0), end: Offset.zero)
            .animate(_controller);

    _offsetFloat.addListener(() {
      setState(() {});
    });

    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double height100 = MediaQuery.of(context).size.height;
    double width100 = MediaQuery.of(context).size.width;
    return new SlideTransition(
      position: _offsetFloat,
      child: Container(
        color: Colors.cyan,
        width: 0.525 * width100 - 3.0,
        child: Text("hello there sailor"),
      ),
    );
  }
}

Answer:

The animation looks like it is not happening because the distance it moves is huge. The Offset passed to the SlideTransition, is relative to its child size. For example, your child has a width: 100.0 and you offset with Offset(2.0, 0.0), and your child will have moved 200.0 pixels to the right.

Just try to change begin: Offset(widget.widthSlide, 0.0), end: Offset.zero to begin: Offset(2.0, 0.0), end: Offset.zero.

You’ll see the text slowly animating from the right to the center of the screen. So you just need to adjust your parameterization.

So now our output will look like below:

slideTransition Widget - Flutter Widget Guide By Flutter Agency

Conclusion:

So in this article, we learned about What is SlideTransition Widget in Flutter along with how to implement it in a Flutter.

Thanks for being with us on a Flutter Journey !!!

Keep Fluttering!! Keep Learning!!

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields