Search code examples
flutteranimationtranslationslide

How to make the image shift up in flutter


I am recently studying about animation like SlideTransition in flutter. What I would like to do is showing an image from the center of a screen page, and then after 3 seconds I would like to make the image shift a few centimeters up from the center. Is there a way to do that ?


Solution

  • Please check out the following code:

    import 'package:flutter/material.dart';
    
    class TransitionUpAnimation extends StatefulWidget {
      const TransitionUpAnimation({Key? key}) : super(key: key);
    
      @override
      State<TransitionUpAnimation> createState() => _TransitionUpAnimationState();
    }
    
    class _TransitionUpAnimationState extends State<TransitionUpAnimation>
        with TickerProviderStateMixin {
      AnimationController? _controller;
      Animation<Offset>? _animation;
      @override
      void initState() {
        super.initState();
        _controller = AnimationController(
          duration: const Duration(seconds: 1),
          vsync: this,
        );
        _animation = Tween<Offset>(
          begin: const Offset(0.0, 0.0),
          end: const Offset(0.0, -2),
        ).animate(CurvedAnimation(
          parent: _controller!,
          curve: Curves.easeInCubic,
        ));
        Future.delayed(const Duration(milliseconds: 3000), () {
          _controller!.forward();
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: SlideTransition(
              position: _animation!,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.red,
              ),
            ),
          ),
        );
      }
    }
    

    Output: