I want my widget to animate moving to a random part of the screen whenever i tap on a button

Viewed 660

Basically I have a widget and a floatingActionButton, i want to make that widget move whenever i press the button, i managed to make it teleport to a random location, but i want it animated.

I would like my widget to animate going from his current location to a new location when pressing the button.

Also the randomNumber() function is a function that picks a random number between a minimum and a maximum. randomNumber(min,max);

class _homePageState extends State<homePage> with SingleTickerProviderStateMixin{

  late final AnimationController _animationController = AnimationController(
    vsync: this,
    duration: Duration(seconds: 1),
  )..forward();


  @override
  void initState() {

    super.initState();
  }

  double beginX = randomNumber(-1, 1);
  double beginY = randomNumber(-1, 1);

  double endX = randomNumber(-1, 1);
  double endY = randomNumber(-1, 1);

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

  @override
  Widget build(BuildContext context) {

    late final Animation<Offset> _animation = Tween<Offset>(
      begin: Offset(beginX, beginY),
      end: Offset(endX, endY),
    ).animate(_animationController);

    return Scaffold(
      body: Center(
          child: SlideTransition(
            child: Container(
                height: 100,
                width: 100,
                color: Colors.red,
            ),
            position: _animation,
          )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {

            beginX = endX; // here i wanted the widget's old end position to become it's new begin position
            beginY = endY;

            endX = randomNumber(-1, 1);
            endY = randomNumber(-1, 1);

            _animationController..forward();

          });
        },
      ),
    );
  }
}
1 Answers

you could set up your own animations and do it that way, nut it would be a lot simpeler to just use a Stack and an AnimatedPositioned then you'd just have to update some random position values and rebuild the widget.

the docs have all the info

Related