有很多方法可以实现这一目标。这只是一个例子:
class LogoApp extends StatefulWidget {
_LogoAppState createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with TickerProviderStateMixin {
Animation animation;
Animation animationOpacity;
AnimationController controller;
initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000), vsync: this);
final CurvedAnimation curve =
CurvedAnimation(parent: controller, curve: Curves.easeIn);
animation = Tween(begin: 0.0, end: 300.0).animate(curve);
animationOpacity = Tween(begin: 0.0, end: 1.0).animate(curve);
controller.forward();
}
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, widget) {
return Opacity(
opacity: animationOpacity.value,
child: Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
height: animation.value,
width: animation.value,
child: FlutterLogo(),
),
);
},
);
}
dispose() {
controller.dispose();
super.dispose();
}
}
用法:
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: Material(child: Center(child: LogoApp())));
}
请参阅本文档 Flutter Animations
更新
class LogoApp extends StatefulWidget {
_LogoAppState createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with TickerProviderStateMixin {
Animation controllerAnimation;
AnimationController controller;
initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 1000), vsync: this);
final CurvedAnimation curve =
CurvedAnimation(parent: controller, curve: Curves.easeIn);
controllerAnimation = Tween(begin: 0.0, end: 1.0).animate(curve);
controller.forward();
}
bool isSelected = false;
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedSwitcher(
duration: Duration(seconds: 10),//it is ignored
child: isSelected
? Container(
width: 200.0,
height: 200.0,
child: FlutterLogo(
colors: Colors.red,
),
)
: Container(
width: 200.0,
height: 200.0,
child: FlutterLogo(
colors: Colors.blue,
)),
transitionBuilder: defaultTransitionBuilder,
),
MaterialButton(
child: Text("Texting"),
onPressed: () {
if (controller.isCompleted) {
controller.reset();
}
controller.forward();
setState(() {
isSelected = !isSelected;
});
},
)
],
);
}
Widget defaultTransitionBuilder(Widget child, Animation<double> animation) {
return AnimatedBuilder(
animation: controller,
builder: (context, widget) {
return Opacity(
opacity: controllerAnimation.value,
child: ScaleTransition(
scale: controllerAnimation,
child: widget,
),
);
},
child: child,
);
}
dispose() {
controller.dispose();
super.dispose();
}
}