Home > front end >  Flutter How can I make this animation "smoother"
Flutter How can I make this animation "smoother"

Time:12-10

How can I make this animation "smoother" (currently is restarts harshly on the 5 second refresh). I'd like for it to reverse maybe from the last angle?

I call this widget as this:

   SpinnerAnimation(body: Icon(FontAwesomeIcons.earthAmericas, size: 33, color: Colors.white,),),

import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';

class SpinnerAnimation extends StatefulWidget {
  late final Widget body;

  SpinnerAnimation({required this.body});

  @override
  _SpinnerAnimationState createState() =>
      _SpinnerAnimationState(body: this.body);
}

class _SpinnerAnimationState extends State<SpinnerAnimation>
    with SingleTickerProviderStateMixin {
  late final Widget body;

  _SpinnerAnimationState({required this.body});

  late AnimationController _controller;
  double change_rotation_speed = 1.2;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 10),
      vsync: this,
    )..repeat();

    //timer repeat every 5 seconds:
     Timer.periodic(Duration(seconds: 5), (Timer t) => change_rotation_speed = randoDoubleGeneratorWithRange(1.2, 5) );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      child: body,
      builder: (BuildContext context, Widget? child) {
        return Transform.rotate(
          angle: _controller.value * change_rotation_speed * math.pi,
          child: child,
        );
      },
    );
  }
double randoDoubleGeneratorWithRange(double min, double max) {
 //return a random double value:
  var random = new Random();
  double result = min   random.nextDouble() * (max - min);
  //print(result);
  return result;
 }
}

CodePudding user response:

You can use RotationTransition and with Animation

.............
 late AnimationController _controller;
  late Animation<double> animationRotation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    )..repeat(revere:true); // set true for reverse animation

    animationRotation =
        Tween<double>(begin: 0.0, end: 1.0).animate(_controller);
  }
........

 @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      child: body,
      builder: (BuildContext context, Widget? child) {
        return RotationTransition(
          turns: animationRotation,
          child: child,
        );
      },
    );

here demo link on Dartpad: enter image description here

  • Related