Learn How to Animate Widget Position in Flutter 2023

Article by: Manish Methani

Last Updated: September 21, 2021 at 8:04am IST
6 min 59 sec

Table of Contents

Introduction

Flutter is an open-source mobile application development framework created by Google. It allows you to build high-performance, cross-platform applications with a single codebase. In this tutorial, we will learn how to animate widget position in Flutter using the AnimatedPositioned widget.

Setting up the Flutter project

Before we begin, make sure you have Flutter installed on your machine. If you don't, you can follow the installation guide provided in the official Flutter documentation.

Once you have Flutter installed, create a new Flutter project using the following command:

flutter create animated_positioned_demo

Creating the AnimatedPositioned widget

The AnimatedPositioned widget is a Flutter widget that animates its position within its parent widget. To use the AnimatedPositioned widget, we need to first create a container widget with a fixed size that will act as the parent widget for our AnimatedPositioned widget.

Here's an example of how to create a container widget with a fixed size:

Container(
  height: 200.0,
  width: 200.0,
  color: Colors.blue,
  child: // Child widgets will go here
),

Next, we need to create our AnimatedPositioned widget and add it as a child to our container widget. Here's an example of how to create an AnimatedPositioned widget:

AnimatedPositioned(
  duration: Duration(milliseconds: 500),
  curve: Curves.easeInOut,
  top: 0.0,
  left: 0.0,
  child: // Child widgets will go here
),

In the code above, we've created an AnimatedPositioned widget with a duration of 500 milliseconds and an ease-in-out curve. We've also set the initial position of the widget to the top-left corner of the parent container by setting the top and left properties to 0.0.

Animating the widget position

To animate the position of our AnimatedPositioned widget, we need to change the values of its top and left properties. We can do this by wrapping our AnimatedPositioned widget in an AnimatedBuilder widget and updating the values of top and left in its builder function.

Here's an example of how to animate the position of our AnimatedPositioned widget:

class MyHomePage extends StatefulWidget {
  @override
  State createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
  bool _isPositionedRight = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Widget Position'),
      ),
      body: Center(
        child: Stack(
          children: [
            AnimatedPositioned(
              duration: Duration(seconds: 1),
              curve: Curves.easeInOut,
              left: _isPositionedRight ? 200.0 : 0.0,
              child: Container(
                width: 100.0,
                height: 100.0,
                color: Colors.blue,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _isPositionedRight = !_isPositionedRight;
          });
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

In the code above, we've created an AnimatedBuilder widget that takes an Animation object as its argument.

Complete Code for Reference

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
       
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  bool _isPositionedRight = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Widget Position'),
      ),
      body: Center(
        child: Stack(
          children: [
            AnimatedPositioned(
              duration: Duration(seconds: 1),
              curve: Curves.easeInOut,
              left: _isPositionedRight ? 200.0 : 0.0,
              child: Container(
                width: 100.0,
                height: 100.0,
                color: Colors.blue,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _isPositionedRight = !_isPositionedRight;
          });
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

Conclusion

In this tutorial, we've learned how to animate widget position in Flutter using the AnimatedPositioned widget. We've also learned how to wrap our AnimatedPositioned widget in an AnimatedBuilder widget to update its position using an animation.

By following the steps outlined in this tutorial, you should now be able to create animated widgets that change position within their parent widgets in your Flutter applications.

Frequently Asked Questions

Q: What is the AnimatedPositioned widget in Flutter?

A: The AnimatedPositioned widget is a built-in Flutter widget that animates the position and size of its child widget.

Q: How do I use the AnimatedPositioned widget to animate the position of a widget in Flutter?

A: To use the AnimatedPositioned widget, wrap the widget you want to animate with it and set the desired animation properties, such as duration and curve. Then, update the widgets position or size by setting the appropriate properties, such as left or top for position.

Q: Can I animate the position of any widget in Flutter?

A: Yes, you can animate the position of any widget in Flutter by wrapping it with the AnimatedPositioned widget and updating its position properties.

Q: How do I trigger the animation of the widget position?

A: You can trigger the animation of the widget position by changing the properties of the AnimatedPositioned widget, such as left or top, and Flutter will animate the position change automatically.

Q: Can I apply different animation curves to the widget position animation?

A: Yes, you can apply different animation curves to the widget position animation by setting the curve property of the AnimatedPositioned widget to a predefined Flutter animation curve, or create your own custom curve.

Q: Can I animate the position of multiple widgets simultaneously in Flutter?

A: Yes, you can animate the position of multiple widgets simultaneously in Flutter by wrapping each widget with an AnimatedPositioned widget and setting their respective position properties. However, you will need to coordinate the animation properties to ensure that the widgets animate smoothly together.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test
include_once 'codzify-footer.php'; ?>