Flutter - 图标颜色变化期间平滑过渡

问题描述 投票:0回答:1

我目前正在使用 Flutter 开发一个应用程序,我试图在更改图标颜色时实现平滑过渡。

这是我的图标的代码:

 Icon(
      widget.icon!,
      color: isFocused ? Colors.blue : Colors.grey,
 ),

我想实现持续时间为 125 毫秒的转换。

预先感谢您的帮助。

flutter user-interface animation icons transition
1个回答
0
投票

我已经编写了自己的小部件,您当然可以根据需要调整变量名称,isFocused这里称为isBlue。 您还可以更改课堂上的颜色和持续时间

class ColorChangeIcon extends StatefulWidget {
final bool isBlue;
final IconData icon;

ColorChangeIcon({required this.isBlue, required this.icon});

@override
_ColorChangeIconState createState() => _ColorChangeIconState();
}

class _ColorChangeIconState extends State<ColorChangeIcon>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Color?> _animation;

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

_animation = ColorTween(
  begin: Colors.blue,
  end: Colors.grey,
).animate(_controller);

if (!widget.isBlue) {
  _controller.forward();
}
}

@override
void didUpdateWidget(ColorChangeIcon oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.isBlue != oldWidget.isBlue) {
  if (widget.isBlue) {
    _controller.reverse();
  } else {
    _controller.forward();
  }
 }
}

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

@override
Widget build(BuildContext context) {
return AnimatedBuilder(
  animation: _animation,
  builder: (context, child) {
    return Icon(
      widget.icon,
      color: _animation.value,
    );
  },
 );
}
}
© www.soinside.com 2019 - 2024. All rights reserved.