ILii
ILii

Reputation: 99

change icon color when sliding animation to top in flutter

I need to change the color of the icon while sliding to the top. Using two colors, one at the beginning and the second at the end. I tried this code below, but the color remains the same.

class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);
  static String tag = '/Loading';

  @override
  State<Loading> createState() => _LoadingState();
}

class _LoadingState extends State<Loading> with TickerProviderStateMixin {
  late AnimationController controller, colorController;
  late Animation<Offset> offset;
  late Animation animation;

  @override
  void initState() {
    super.initState();

    controller =
        AnimationController(duration: Duration(seconds: 1), vsync: this);
    Future.delayed(Duration(milliseconds: 100))
        .then((_) => controller.forward());

    offset = Tween<Offset>(begin: Offset(0.0, 10.0), end: Offset.zero)
        .animate(controller);

    colorController = AnimationController(
      duration:
          const Duration(milliseconds: 5000), //controll animation duration
      vsync: this,
    );

    animation = ColorTween(
      begin: Colors.grey,
      end: Colors.red,
    ).animate(colorController);
  }

  // @override
  // void dispose() {
  //   controller2.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
      alignment: Alignment.center,
      child: SlideTransition(
        position: offset,
        child: Icon(
          Icons.favorite,
          color: animation.value,
        ),
      ),
    ));
  }
}

Upvotes: 1

Views: 441

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You are missing to call forward on colorController and to change the UI use addListener to call setState.

colorController = AnimationController(
  duration: const Duration(milliseconds: 500),  
  vsync: this,
)
  ..addListener(() {
    setState(() {});
  })
  ..forward();

Upvotes: 2

Related Questions