在Flutter
开发当中,如果我们不需要实现单独的继承AnimatedWidget
自定义动画组件,我们可以通过AnimatedBuilder
组件来实现相同效果的动画。这篇博客分享AnimatedBuilder
组件的简单使用,希望对看文章的小伙伴有所帮助。
AnimatedBuilder简单用法
核心代码:
AnimatedBuilder(
animation: controller,
builder: (BuildContext context, Widget? child) {
return Container(
height: 200,
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: const [Colors.yellow, Colors.red],
stops: [0, controller.value])),
);
},
)
完整代码:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: '动画 Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
late Animation<double> animation;
late AnimationController controller;
@override
void initState() {
super.initState();
controller =
AnimationController(duration: const Duration(seconds: 1), vsync: this);
animation = Tween<double>(begin: 0, end: 1.0).animate(controller);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: AnimatedBuilder(
animation: controller,
builder: (BuildContext context, Widget? child) {
return Container(
height: 200,
padding: const EdgeInsets.all(10),
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: const [Colors.yellow, Colors.red],
stops: [0, controller.value])),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 点击事件,设置动画开始
if (controller.status == AnimationStatus.completed) {
controller.reverse();
} else {
controller.forward();
}
},
child: const Icon(Icons.play_arrow),
),
);
}
@override
void dispose() {
super.dispose();
controller.dispose();
}
}
实现的效果如下,两种效果可以通过右下角的按钮来切换: