The AnimatedPositioned widget in Flutter is used to animate changes to the position of its child widget within a Stack. It's particularly useful when you want to move a widget from one position to another smoothly, allowing for dynamic layout changes with animation.
Attributes:
child (Widget):
- The child widget that is positioned within the AnimatedPositioned widget.
left (double):
- The distance by which the left edge of the child widget is inset from the left edge of its parent widget.
top (double):
- The distance by which the top edge of the child widget is inset from the top edge of its parent widget.
right (double):
- The distance by which the right edge of the child widget is inset from the right edge of its parent widget.
bottom (double):
- The distance by which the bottom edge of the child widget is inset from the bottom edge of its parent widget.
width (double):
- The width of the child widget.
height (double):
- The height of the child widget.
duration (Duration):
- The duration over which the position change should be animated.
curve (Curve):
- The animation curve to use for animating the position change.
Example:
import 'package:flutter/material.dart';
class AnimatedPositionedExample extends StatefulWidget {
@override
_AnimatedPositionedExampleState createState() => _AnimatedPositionedExampleState();
}
class _AnimatedPositionedExampleState extends State<AnimatedPositionedExample> {
bool _isMoved = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedPositioned Example'),
),
body: Stack(
children: [
AnimatedPositioned(
left: _isMoved ? 100 : 0,
top: _isMoved ? 100 : 0,
duration: Duration(seconds: 1),
curve: Curves.easeInOut,
child: Container(
width: 100,
height: 100,
color: Colors.blue,
child: Center(
child: Text(
'AnimatedPositioned',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_isMoved = !_isMoved;
});
},
child: Icon(Icons.play_arrow),
),
);
}
}
void main() {
runApp(MaterialApp(
home: AnimatedPositionedExample(),
));
}
In this example:
An AnimatedPositioned widget is used to animate changes to the position of a Container widget within a Stack.
The left and top attributes are set based on the _isMoved flag, which toggles between 0 and 100.
The duration attribute is set to Duration(seconds: 1), specifying the duration of the animation.
The curve attribute is set to Curves.easeInOut, defining the animation curve for the position change.
When the user presses the floating action button, the _isMoved flag is toggled, triggering the animation of the position change.