Home > Net >  How to animate color transitions in flutter?
How to animate color transitions in flutter?

Time:12-09

I'm creating a custom checkbox-like widget that uses Card. I'm able to get the colors changing if the values are the same onTap. However, I want it to transition the color instead of it suddenly changing.

Here's my code:

return Card(
      color: selected ? AppColors.primary : AppColors.primaryLight,

I'm relatively new to animations in Flutter, but coming from a strong Frontend/CSS understanding, the way I could achieve something like this is to add transition on a CSS property -- is there something similar to this in Flutter? If not, could someone point me in the right direction?

CodePudding user response:

What I would do is instead of using the Card widget, I would use an AnimatedContainer and have the same condition as you for the color parameter. You will get a smooth transition when the selected value changes. However, you may need to also add boxShadow to have the same elevation effect as Card

AnimatedContainer(
 duration: const Duration(milliseconds: 700),
 curve: Curves.easeInOut,
 decoration:BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.black,
        blurRadius: 5,
        spreadRadius: 5,
        offset: Offset(0, 2),
      ),
    ],
    color: selected ? AppColors.primary : AppColors.primaryLight,
    ),
   )

CodePudding user response:

One way to do this would be an AnimatedContainer

return Card(
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 1000),
          height: 200,
          width: 200,
          color: selected ? Colors.red : Colors.blue,
          child: FooWidget(),
        ),
      )
  • Related