Skip to content

Instantly share code, notes, and snippets.

@emvaized
Last active July 8, 2021 07:47
Show Gist options
  • Save emvaized/9660d975a11d614eb4b37a749f380214 to your computer and use it in GitHub Desktop.
Save emvaized/9660d975a11d614eb4b37a749f380214 to your computer and use it in GitHub Desktop.
AnimatedOffset widget for Flutter — animated version of Transform.translate
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class AnimatedOffset extends ImplicitlyAnimatedWidget {
/// Animated version of [Transform.translate] which automatically transitions the child's
/// offset over a given duration whenever the given offset changes.
///
/// The [curve] and [duration] arguments must not be null.
const AnimatedOffset({
Key? key,
this.child,
required this.offset,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
}) :
super(key: key, curve: curve, duration: duration, onEnd: onEnd);
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// The target offset.
/// The child will be translated horizontally by `width * dx` and vertically by `height * dy`
///
/// The offset must not be null.
final Offset offset;
@override
_AnimatedOffsetState createState() => _AnimatedOffsetState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
}
}
class _AnimatedOffsetState extends ImplicitlyAnimatedWidgetState<AnimatedOffset> {
Tween<Offset>? _offset;
late Animation<Offset> _offsetAnimation;
@override
void forEachTween(TweenVisitor<dynamic> visitor) {
_offset = visitor(_offset, widget.offset, (dynamic value) => Tween<Offset>(begin: value as Offset)) as Tween<Offset>?;
}
@override
void didUpdateTweens() {
_offsetAnimation = animation.drive(_offset!);
}
@override
Widget build(BuildContext context) {
return SlideTransition(
position: _offsetAnimation,
child: widget.child,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment