简体   繁体   中英

How to animate color transitions in flutter?

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?

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,
    ),
   )

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(),
        ),
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM