SlideTransition Widget – Flutter Widget Guide By Flutter Agency

· 9 min read
SlideTransition Widget - Flutter Widget Guide By Flutter Agency
SlideTransition Widget - Flutter Widget Guide By Flutter Agency

Earlier we have been through Transition Widget in Flutter like ScaleTransition WidgetRotationTransition WidgetFadeTransition Widget. So now let us add one more Transition Widget to the list that is SlideTransition Widget.

What is SlideTransition Widget in Flutter?

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:

SlideTransitionWidget({
  Key key,
  @required Animation<Offset> 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.

AnimationController _controller;
Animation<Offset> _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<Offset>(
    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: RaisedButton(
              child: Text('Slide Transition Widget'),
              onPressed: () {
                Scaffold.of(context).showSnackBar(
                  SnackBar(
                    content: Text('Button is pressed'),
                  ),
                );
              },
            ),
          ),
        ),
      ),

So now our complete code snippet will look like below:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class SlideTransitionWidget extends StatefulWidget {
  @override
  __SlideTransitionWidgetState createState() =>
      new __SlideTransitionWidgetState();
}

class __SlideTransitionWidgetState extends State<SlideTransitionWidget>
    with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<Offset> _animation;

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

    _controller = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    )..forward();
    _animation = Tween<Offset>(
      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: RaisedButton(
              child: Text('SlideTransition'),
              onPressed: () {
                Scaffold.of(context).showSnackBar(
                  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:
    return Column(
       children: <Widget>[
         SlideTransition(
             position:_curve1,
             child: Text('Hello 1')
         ),
         SlideTransition(
             position:_curve1,
             child: Text('Hello 2')
         ),
         SlideTransition(
             position:_curve1,
             child: Text('Hello 3')
         ),
       ]
    );

    initState() will look like below:

    @override
    void initState(){
        ...
        Offset beginningOffset = Offset(0.0,20.0);
        _curve1 = Tween<Offset>(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();
   new 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.

class DeleteCheck extends StatefulWidget{

  final offsetBool;
  final double widthSlide;

  DeleteCheck({
    Key key, 
    this.offsetBool, 
    this.widthSlide
  }): super(key: key);

  @override 
  State<StatefulWidget> createState() {
    return new _MyDeleteCheck();
  }
}

class _MyDeleteCheck extends State<DeleteCheck> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<Offset> _offsetFloat; 

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

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

    _offsetFloat = Tween<Offset>(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!!

FlutterAgency.com 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.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply