探索 Flutter Effects: 打造生动有趣的 UI 动画
在Flutter中创建一个简单的UI动画可以使用AnimatedContainer
或AnimatedOpacity
。以下是一个使用AnimatedOpacity
创建淡入淡出动画的示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
AnimationController controller;
Animation<double> opacityAnimation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(controller);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
void _toggleAnimation() {
if (controller.isAnimating) {
controller.stop();
} else {
controller.forward();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('动画示例'),
),
body: Center(
child: AnimatedOpacity(
opacity: opacityAnimation.value,
duration: const Duration(milliseconds: 500),
child: FlatButton(
color: Colors.blue,
child: Text('点击我'),
onPressed: _toggleAnimation,
),
),
),
);
}
}
这段代码定义了一个有着AnimatedOpacity
的FlatButton
,通过控制opacityAnimation
的值来实现按钮的淡入淡出效果。AnimationController
负责动画的进程,通过_toggleAnimation
方法来控制动画的播放和暂停。
评论已关闭