添加颜色过渡

Posted

技术标签:

【中文标题】添加颜色过渡【英文标题】:Add color transitions 【发布时间】:2021-04-23 17:23:39 【问题描述】:

我正在尝试使一种颜色为从绿色到琥珀色再到红色的颜色设置动画。在升级到 null-safety 之前,以下代码运行良好,但现在它抛出错误......

TweenSequence<Color>([
  TweenSequenceItem(weight: 0.5, tween: ColorTween(begin: Colors.green, end: Colors.green)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.green, end: Colors.amber)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.amber, end: Colors.red)),
])

我收到以下错误:

无法将参数类型“ColorTween”分配给参数类型 '动画

我做错了什么,我该如何解决?

更新:

AnimationController(duration: Duration(seconds: 10), vsync: this).drive(TweenSequence<Color?>([
  TweenSequenceItem(weight: 0.5, tween: ColorTween(begin: Colors.green, end: Colors.green)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.green, end: Colors.amber)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.amber, end: Colors.red)),
]));

【问题讨论】:

【参考方案1】:

如果您查看ColorTween 的继承,您会发现它是Animatable&lt;Color?&gt; 的子类型,而您的TweenSequence 使用不兼容的Color 泛型。

只需将Color 更改为Color?

TweenSequence<Color?>([
  TweenSequenceItem(weight: 0.5, tween: ColorTween(begin: Colors.green, end: Colors.green)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.green, end: Colors.amber)),
  TweenSequenceItem(weight: 0.25, tween: ColorTween(begin: Colors.amber, end: Colors.red)),
])

【讨论】:

谢谢!现在我得到一个差异错误:我将颜色补间序列分配给 AnimationController.drive。我收到以下错误:无法将参数类型“TweenSequence”分配给参数类型“Animatable。我已经尝试将类型更改为 Animatable 但仍然给出错误 @Jessica 请在您的问题中分享该代码。 @Jessica 你遇到 linter 错误还是什么?我在 DartPad 上看不到您的代码有任何错误。

以上是关于添加颜色过渡的主要内容,如果未能解决你的问题,请参考以下文章