Skip to content

Instantly share code, notes, and snippets.

@joaortk
Created August 1, 2019 14:05
Show Gist options
  • Save joaortk/d62f5d61052dc87e44eddc2e0a1a97f4 to your computer and use it in GitHub Desktop.
Save joaortk/d62f5d61052dc87e44eddc2e0a1a97f4 to your computer and use it in GitHub Desktop.
import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';
class SpringAnimated extends StatefulWidget {
final Widget child;
final Offset startOffset;
final bool shouldResetOffset;
SpringAnimated(
{@required this.child,
@required this.startOffset,
this.shouldResetOffset});
@override
State<StatefulWidget> createState() {
return SpringAnimatedState();
}
}
class SpringAnimatedState extends State<SpringAnimated>
with SingleTickerProviderStateMixin {
AnimationController _animationController;
Offset _offset;
SpringSimulation spring;
SpringAnimatedState();
@override
void initState() {
super.initState();
_offset = widget.startOffset;
_animationController = new AnimationController(
vsync: this,
lowerBound: double.negativeInfinity,
upperBound: double.infinity,
duration: Duration(milliseconds: 900));
_animationController.addStatusListener(statusListener);
Tween(
begin: -2,
end: 0,
).animate(
CurvedAnimation(
parent: _animationController,
curve: Interval(0, 2),
),
);
_animationController.forward(from: -2);
}
void statusListener(status) {
if (status == AnimationStatus.completed) {
_animationController.removeStatusListener(statusListener);
_animationController.addListener(() {
setState(() {
_offset = Offset(_animationController.value, 0);
});
});
_animationController.animateWith(
SpringSimulation(
SpringDescription(mass: 1.0, stiffness: 100.0, damping: 10.0),
_offset.dx,
0.0,
_animationController.velocity,
),
);
}
}
@override
Widget build(BuildContext context) {
var x = Transform.translate(
offset: _offset,
child: widget.child,
);
if (widget.shouldResetOffset) {
_offset = widget.startOffset;
_animateWithTranslation();
}
return x;
}
_animateWithTranslation() {
_animationController
.animateTo(_offset.dx,
duration: Duration(milliseconds: 150), curve: Curves.linear)
.whenComplete(() {
_animationController.animateWith(
SpringSimulation(
SpringDescription(mass: 1.0, stiffness: 100.0, damping: 10.0),
_offset.dx,
0.0,
_animationController.velocity,
),
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment