具有两种不同类型动画的AnimatedBuilder不起作用



我正在尝试为CircularProgressIndicator的颜色和值设置动画,我希望它在15秒内从0-1从粉色变为橙色。这是我尝试过的一切:

TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: 1),
curve: Curves.easeOut,
duration: Duration(seconds: 15),
builder: (context, value, _) {
Color strokeColor = Colors.pink;
if (value > 0.5) strokeColor = Colors.orange;
return CircularProgressIndicator(
strokeWidth: 8, value: value, valueColor: AlwaysStoppedAnimation<Color>(strokeColor));
}),

设置了值的动画,但没有设置值颜色/笔划颜色的动画。我必须以某种方式将ColorTween(begin: Colors.pink, end: Colors.orange)传递给值Color,但我不确定如何。。。我用AnimatedBuilder替换了TweenAnimationBuilder,但我遇到了问题,因为动画只能使用1种类型的值,即双色或彩色,但不能同时使用。。。

可以使用AnimatedBuilder传递ColorTween和Tween来分别控制CircularProgressIndicator的颜色和值。

为了做到这一点:

  1. 我们需要在我们的父StatefulWidget上使用SingleTikerProviderStateMixin:
class _MyProgressIndicator extends State<MyProgressIndicator>
with SingleTickerProviderStateMixin {
// ...
}
  1. 初始化AnimationController、ColorTweenTween<double>,并通过重写initState()方法启动AnimationController
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 15),
vsync: this,
);
_animationColor = ColorTween(
begin: Colors.pink,
end: Colors.orange,
).animate(_controller);
_animationValue = Tween<double>(begin: 0, end: 1).animate(_controller);
_controller.forward();
}
  1. 不要通过重写dispose()方法来忘记AnimationController
@override        
void dispose() {            
_controller.dispose();            
super.dispose();            
}

完整的示例如下所示:

import 'package:flutter/material.dart';
class MyProgressIndicator extends StatefulWidget {
MyProgressIndicator({Key key}) : super(key: key);
@override
_MyProgressIndicator createState() => _MyProgressIndicator();
}
class _MyProgressIndicator extends State<MyProgressIndicator>
with SingleTickerProviderStateMixin {
Animation<Color> _animationColor;
Animation<double> _animationValue;
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 15),
vsync: this,
);
_animationColor = ColorTween(
begin: Colors.pink,
end: Colors.orange,
).animate(_controller);
_animationValue = Tween<double>(begin: 0, end: 1).animate(_controller);
_controller.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AnimatedBuilder(
animation: _controller,
builder: (BuildContext context, Widget child) {
return CircularProgressIndicator(
strokeWidth: 8,
value: _animationValue.value,
valueColor: _animationColor,
);
},
),
),
);
}
@override        
void dispose() {            
_controller.dispose();            
super.dispose();            
}
}

最新更新