AnimatedRotation for animating compass
I am trying to add a compass to my app. What is the best way to animate the rotation from 359 to 0 or 0 to 359? Is there a better suited widget for this type of rotation?
AnimatedRotation(
duration: const Duration(milliseconds: 250),
turns: -heading / 360.0,
curve: Curves.linear,
Tried to do it by adding the difference instead of assigning the angle but it can overflow if it is rotating on same direction.
if(previousHeading - heading > 180) {
turns += ((360.0 - previousHeading) + heading) / 360.0;
}
else if(previousHeading - heading < -180) {
turns -= ((360.0 - heading + previousHeading)) / 360.0;
}
else {
turns += ((previousHeading - heading) / 360.0);
}
previousHeading = heading;
Solution 1: G H Prakash
Animated version of Transform.rotate which automatically transitions the child's rotation over a given duration whenever the given rotation changes.
For Clear Analysis please check here:
Solution 2: René Lazo
Widget:
AnimatedRotation(
turns: turns,
duration: const Duration(milliseconds: 250),
child: const Icon(Icons.arrow_upward_outlined),
)
To get the correct "turn" value you should do this:
double prevValue = 0.0;
FlutterCompass.events?.listen((CompassEvent event) {
double? direction = event.heading;
direction = direction < 0 ? (360 + direction): direction;
double diff = direction - prevValue;
if(diff.abs() > 180) {
if(prevValue > direction) {
diff = 360 - (direction-prevValue).abs();
} else {
diff = 360 - (prevValue-direction).abs();
diff = diff * -1;
}
}
turns += (diff / 360);
prevValue = direction;
});
I hope this could save some time to others ;)
Solution 3: Fahad Shabir
use smooth compass very easy to use, check here https://pub.dev/packages/smooth_compass